我想将元素列表分成嵌套列表,每个子列表都有连续的元素。如果一个元素没有连续的元素,它应该在单个列表中。
输入:
l1 = [1, 2, 3, 11, 12, 13, 23, 33, 34, 35, 45]
l2 = [11, 12, 13, 22, 23, 24, 33, 34]
l3 = [1, 2, 3, 11, 12, 13, 32, 33, 34, 45]
预期输出:
l1 = [[1, 2, 3], [11, 12, 13], [23], [33, 34, 35], [45]]
l2 = [[11, 12, 13], [22, 23, 24], [33, 34]]
l3 = [[1, 2, 3], [11, 12, 13], [32, 33, 34], [45]]
我已经尝试了下面的代码,但它没有给出预期的结果,打印了一个空列表:
def split_into_list(l):
t = []
for i in range(len(l) - 1):
if abs(l[i] - l[i + 1]) == 0:
t.append(l[i])
elif abs(l[i] - l[i + 1]) != 0 and abs(l[i - 1] - l[i]) == 0:
t.append(l[i])
yield t
split_into_list(l[i:])
if i + 1 == len(l):
t.append(l[i])
yield t
l = [1, 2, 3, 11, 12, 13, 32, 33, 34, 45]
li = []
li.append(split_into_list(l))
for i in li:
print(i, list(i))
最佳答案
使用自定义 split_adjacent
函数的更短方法:
def split_adjacent(lst):
res = [[lst[0]]] # start/init with the 1st item/number
for i in range(1, len(lst)):
if lst[i] - res[-1][-1] > 1: # compare current and previous item
res.append([])
res[-1].append(lst[i])
return res
l1 = [1, 2, 3, 11, 12, 13, 23, 33, 34, 35, 45]
l2 = [11, 12, 13, 22, 23, 24, 33, 34]
l3 = [1, 2, 3, 11, 12, 13, 32, 33, 34, 45]
print(split_adjacent(l1))
print(split_adjacent(l2))
print(split_adjacent(l3))
最终输出:
[[1, 2, 3], [11, 12, 13], [23], [33, 34, 35], [45]]
[[11, 12, 13], [22, 23, 24], [33, 34]]
[[1, 2, 3], [11, 12, 13], [32, 33, 34], [45]]
关于python - 将列表作为嵌套列表,在单独列表中包含连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58432920/