首页 > 解决方案 > 列表中重复值的序列

问题描述

我的程序有问题,我希望有人可以帮助我解决这个问题。基本上我有一个随机生成的包含 20 个值的列表,我想将重复的值放在括号之间(例如,如果列表是[1,2,2,4,5]它应该显示1 ( 2 2 ) 4 5 ) 现在这是我的代码,只有在最后没有重复值时才有效,因为列表索引超出范围。我该如何解决这个问题?

from random import randint
lanci = []
for i in range(20):
    x = randint(1,6)
    lanci.append(x)
print(lanci)
i=0
while i < len(lanci)-1):
    if lanci[i] == lanci[i+1]:
        print("(",end=" ")
        print(lanci[i],end=" ")
        while lanci[i]==lanci[i+1]:
            i = i + 1 
            print(lanci[i],end=" ")
    print(")",end=" ")
else:
    print(lanci[i],end=" ")
    i = i + 1  

标签: pythonarrayspython-3.xlist

解决方案


除了您更手动的方法之外,您可以使用itertools.groupby在列表中对相等的值进行分组,然后将它们括在括号中:

>>> import random, itertools
>>> lst = [random.randint(1, 5) for _ in range(20)]
>>> tmp = [list(map(str, g)) for k, g in itertools.groupby(lst)]
>>> ' '.join(g[0] if len(g) == 1 else "(" + " ".join(g) + ")" for g in tmp)
'5 4 1 2 1 4 (5 5) 4 5 1 5 4 3 (5 5) 3 (5 5 5)'

推荐阅读