[英]How to convert list to list of list for adjacent numbers
[31, 32,33, 1,2,3,4, 11,12,13,14]
我有列表[31, 32,33, 1,2,3,4, 11,12,13,14]
Expected out [[1,2,3,4], [11,12,13,14], [31, 32,33]]
预计[[1,2,3,4], [11,12,13,14], [31, 32,33]]
l = [31, 32,33, 1,2,3,4, 11,12,13,14]
l.sort() #sorted the items
new_l = []
for i in l:
temp_l = [] # temp list before appending to main list
if i + 1 in l: # if i + 1 is present append to temp_list
temp_l.append(i)
new_l.append(temp_l) # temp_l has to append to main list
My out is wrong: [[1], [2], [3], [], [11], [12], [13], [], [31], [32], []]
我的出局是错误的: [[1], [2], [3], [], [11], [12], [13], [], [31], [32], []]
You can use itertools.groupby
:您可以使用itertools.groupby
:
from itertools import groupby
l = [31, 32, 33, 1, 2, 3, 4, 11, 12, 13, 14]
l.sort()
out = [
list(v for _, v in g)
for _, g in groupby(enumerate(l), key=lambda v: v[0] - v[1])
]
print(out)
Prints:印刷:
[[1, 2, 3, 4], [11, 12, 13, 14], [31, 32, 33]]
Without itertools.groupby
:没有itertools.groupby
:
l = [31, 32, 33, 1, 2, 3, 4, 11, 12, 13, 14]
l.sort()
out = [[l[0]]]
for i in range(1, len(l)):
if l[i] - out[-1][-1] == 1:
out[-1].append(l[i])
else:
out.append([l[i]])
print(out)
Edit: Added .sort()
编辑:添加.sort()
Use a for
loop, enumerate()
and sort()
使用for
循环、 enumerate()
和sort()
l = [31, 32, 33, 1, 2, 3, 4, 11 ,12, 13, 14]
# sort list
l = sorted(l)
sub_l = []
new_list = []
for i, num in enumerate(l):
# check if not last element
if not (i + 1) == len(l):
# check if next element is the same as the current + 1
if num + 1 == l[i+1]:
sub_l.append(num)
else:
# append sub-list to parent-list and reset sub-list
new_list.append(sub_l)
sub_l = []
print(new_list)
Output Output
[[1, 2, 3], [11, 12, 13], [31, 32]]
You can append an empty sub-list to the output list when the difference between the current number and the last number in the last sub-list in the output list is not 1, and keep appending the current number to the last sub-list of the output list:当当前编号与 output 列表中最后一个子列表中的最后一个编号之间的差异时,您可以将 append 一个空子列表添加到 output 列表中output 列表:
l = [31, 32,33, 1,2,3,4, 11,12,13,14]
l.sort()
output = []
for i in l:
if not output or i - output[-1][-1] != 1:
output.append([])
output[-1].append(i)
output
becomes: output
变为:
[[1, 2, 3, 4], [11, 12, 13, 14], [31, 32, 33]]
Demo: https://replit.com/@blhsing/UnimportantValidTelecommunications演示: https://replit.com/@blhsing/UnimportantValidTelecommunications
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.