Python – 列表中的相邻元素


當需要顯示清單中的相鄰元素時,定義一個方法,該方法使用列舉和簡單疊代來確定結果。

範例

以下是對此方法的演示 −

Open Compiler
def find_adjacent_elements(my_list): my_result = [] for index, ele in enumerate(my_list): if index == 0: my_result.append((None, my_list[index + 1])) elif index == len(my_list) - 1: my_result.append((my_list[index - 1], None)) else: my_result.append((my_list[index - 1], my_list[index + 1])) return my_result my_list = [13, 37, 58, 12, 41, 25, 48, 19, 23] print("The list is:") print(my_list) print("The result is :") print(find_adjacent_elements(my_list))

輸出

The list is:
[13, 37, 58, 12, 41, 25, 48, 19, 23]
The result is :
[(None, 37), (13, 58), (37, 12), (58, 41), (12, 25), (41, 48), (25, 19), (48, 23), (19, None)]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

說明

  • 定義一個名為「 find_adjacent_elements 」的方法,該方法接受清單作為參數,並對清單進行列舉。

  • 建立一個空清單。

  • 使用「列舉」反覆運算元素,並根據索引的值來確定輸出。

  • 如果索引值為 0,則將第一個索引中的元素附加到空清單。

  • 如果索引等於清單長度減 1,則將前一個索引中的元素附加到空清單中。

  • 否則,前一個元素和下一個元素都附加到空清單中。

  • 在方法外部定義一個列表,並在主控台上顯示該列表。

  • 通過傳遞所需參數來調用此方法。

  • 輸出顯示在主控台上。

更新於:08-Sep-2021

2K+ 次瀏覽

启动您的 职业生涯

完成课程并获得认证

开始
广告