简体   繁体   English

从具有连续编号的列表中列出列表

[英]Make a list of a list from a list with consecutive numbers

Here is my list 这是我的清单

a = [ 1, 2, 3, 6, 7, 9, 11, 14, 15, 16]

I want to return a new list like this 我想返回这样的新列表

new_a = [ [1,2,3],
          [6,7],
          [9],
          [11],
          [14,15,16]
        ]

I'm pretty lost on how to actually achieve this. 我对如何真正实现这一目标感到迷茫。

Here's what I have tried. 这是我尝试过的。 Don't laugh please 请别笑

#!/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([])]

Thanks stackoverflow a noob like me can learn :DDD #CoDeSwAgg 谢谢stackoverflow一个像我这样的菜鸟可以学习:DDD #CoDeSwAgg

You can do this with a bit of clever itertools work: 您可以通过一些聪明的itertools工具来做到这一点:

[[v[1] for v in vals] for _, vals in itertools.groupby(enumerate(a), key=lambda x: x[1] - x[0])]

To break it down a bit more naturally: 为了更自然地分解它:

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])
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)

This will work if your list is sorted and does not contain duplicates. 如果您的列表已排序且不包含重复项,则此方法将起作用。

If you need to sort the list, please take a look at how to sort in Python 如果您需要对列表进行排序,请查看如何在Python中进行排序

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]]

disclaimer: your list needs to be sorted first 免责声明:您的列表需要首先排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM