Python – 根據下一個較大的值拆分列表


當需要根據下一個較大的值拆分列表時,會使用列表解析、“iter”方法和“islice”方法。

示例

以下是演示:

from itertools import islice

my_list = [11, 22, 33, 34, 45, 26, 87,11]
print("The list is :")
print(my_list)

length_to_split = [2, 5, 3]
print("The split length list is :")
print(length_to_split)

temp = iter(my_list)
my_result = [list(islice(temp, element)) for element in length_to_split]

print("The result is :")
print(my_result)

輸出

The list is :
[11, 22, 33, 34, 45, 26, 87, 11]
The split length list is :
[2, 5, 3]
The result is :
[[11, 22], [33, 34, 45, 26, 87], [11]]

說明

  • 將所需程式包匯入環境中。

  • 定義一個整數列表並在控制檯上顯示。

  • 定義另一個整數列表並在控制檯上顯示。

  • 對列表呼叫“iter”方法並將其賦值給一個變數。

  • 使用列表解析來迭代元素,並使用“islice”方法。

  • 將其轉換為一個列表並賦值給一個變數。

  • 這是控制檯上顯示的輸出。

更新: 2021-09-08

129 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.