这是我的清单
a = [ 1, 2, 3, 6, 7, 9, 11, 14, 15, 16]
我想返回一个像这样的新列表
new_a = [ [1,2,3],
[6,7],
[9],
[11],
[14,15,16]
]
我很失落如何实现这一目标。
这是我尝试过的。请不要笑。
#!/usr/env python
a = [1,2,3,5,7,9,10,11,18,12,20,21]
a.sort()
final=[]
first = a.pop(0)
temp=[]
for i in a:
if i - first == 1:
temp.append(first)
temp.append(i)
first=i
else:
final.append(set(temp))
first=i
temp=[]
print final
[set([1, 2, 3]), set([]), set([]), set([9, 10, 11, 12]), set([])]
感谢stackoverflow,像我这样的菜鸟可以学习:DDD #CoDeSwAgg
答案 0 :(得分:3)
你可以通过一些聪明的itertools来做到这一点:
[[v[1] for v in vals] for _, vals in itertools.groupby(enumerate(a), key=lambda x: x[1] - x[0])]
更自然地分解它:
result = []
groups = itertools.groupby(enumerate(a), key=lambda x: x[1] - x[0])
for _, values in groups:
result.append([v[1] for v in values])
答案 1 :(得分:1)
a = [1, 2, 3, 6, 7, 9, 11, 14, 15, 16]
def group_by_adjacent(l):
groups = []
current_group = []
for item in l:
if len(current_group) == 0 or item - 1 == current_group[-1]:
current_group.append(item)
else:
groups.append(current_group)
current_group = [item]
return groups
print group_by_adjacent(a)
如果您的列表已排序且不包含重复项,则此功能将起作用。
如果您需要对列表进行排序,请查看how to sort in Python
答案 2 :(得分:1)
out = []
for i in xrange(len(a)):
if i == 0:
sub = [a[0]]
elif a[i] == a[i-1]+1:
sub.append(a[i])
else:
out.append(sub)
sub = [a[i]]
out.append(sub)
print out
# [[1, 2, 3], [6, 7], [9], [11], [14, 15, 16]]
免责声明:您的列表需要先排序