我想将元素列表分成嵌套列表,每个子列表都有连续的元素。如果一个元素没有连续的元素,则应该在单个列表中。
输入:
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))
答案 0 :(得分:1)
使用自定义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]]
答案 1 :(得分:0)
def split_into_list(l):
result = [[]]
for i, elt in enumerate(l[1:]):
diff = abs(elt - l[i])
if diff == 1:
# still the same group
result[-1].append(elt)
else:
# new group
result.append([elt])
return result
l = [1,2,3,11,12,13,32,33,34,45]
print(split_into_list(l))
收益
[[2, 3], [11, 12, 13], [32, 33, 34], [45]]
答案 2 :(得分:0)
def split_into_list(l):
t = []
temp = [l[0]]
prev = l[0]
for i in l[1:]:
if i == prev+1:
temp.append(i)
else:
t.append(temp)
temp = [i]
prev = i
return t
请记住,到目前为止,所有解决方案都依赖于排序列表,您在问题中未明确指定。
答案 3 :(得分:0)
def consecutives(x):
np.split(x, np.flatnonzero(np.diff(x) != 1) + 1)
例如,consecutives(l1)
将导致
[array([1, 2, 3]),
array([11, 12, 13]),
array([23]),
array([33, 34, 35]),
array([45])]
如果您需要嵌套列表,则可以应用list
或ndarray.tolist
:
def consecutives(x):
return [a.tolist() for a in np.split(x, np.flatnonzero(np.diff(x) != 1) + 1)]
现在consecutives(l1)
的结果是
[[1, 2, 3], [11, 12, 13], [23], [33, 34, 35], [45]]