python - 列表中重复值的序列
问题描述
我的程序有问题,我希望有人可以帮助我解决这个问题。基本上我有一个随机生成的包含 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
解决方案
除了您更手动的方法之外,您可以使用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)'
推荐阅读
- firebase - 需要帮助在 firebase 数据库参考中连接登录的用户名。Javascript
- kotlin - 当多个 Singles 完成时执行某些操作(又名 combineLatest for Single)
- python - Python初学者-TypeError:'str'对象不可调用
- swift - 如何将自定义对象转换为 Data Swift
- math - 将曲面拟合到 z 值为 3D 的 3 到 100 个点
- intersystems-cache - # 在列之间的缓存中
- c# - 使用 SqlConnection 和 AttachDbFilename 时出现奇怪的错误
- string - 在 hive 中将多列连接为一列
- python-3.x - latex.exc.LatexBuildError: None for `latex.build_pdf()`
- amazon-web-services - 在 Visual Studio 2017 上安装 AWS Toolkit 时出错