我有一個遞增數字的有序串列,范圍從 1-4 或 1-6。我想創建一個串列串列,在下一次發生 1 之前將它們分開。
my_list = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3 ,4]
list_of_lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4]]
uj5u.com熱心網友回復:
一行就夠了:
from itertools import zip_longest
result = [list(range(1, a 1))
for a, b in zip_longest(my_list, my_list[1:])
if b == 1 or b == None]
uj5u.com熱心網友回復:
my_list每次點擊 1 時迭代并創建子串列。
my_list = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3 ,4]
result = []
i = 0
while i<len(my_list):
sub_list = [my_list[i]]
i =1
while i<len(my_list) and my_list[i]>1:
sub_list.append(my_list[i])
i =1
result.append(sub_list)
print(result)
# [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375875.html
上一篇:從給定數字的串列中查找唯一元素
