簡體   English   中英

從具有連續編號的列表中列出列表

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

這是我的清單

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

您可以通過一些聰明的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])
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)

如果您的列表已排序且不包含重復項,則此方法將起作用。

如果您需要對列表進行排序,請查看如何在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]]

免責聲明:您的列表需要首先排序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM