python - 有没有办法在python中“堆叠”一个列表?
问题描述
我正在做一个项目,一个烦人的事情是,当我打印一个列表时('a','a','a','b','c','b')
,它会打印:
a a a b c b
但是,我希望它加入重复值,例如:
a(3) b(2) c
我有一个复杂的功能来执行此操作,但仍然无法正常工作(如下所示),有人有什么建议吗?
def refine(testlist):
repeatfntest=0
prototypelist=testlist.copy()
lengthtest=len(testlist)-1
testlist.sort()
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
finalizedtermsfn=[]
while lengthtest>-1:
repititionfn=1
lengthtest=len(prototypelist)-1
occurences=0
while repititionfn>0:
lengthtest-=1
occurences+=1
print(currentterm)
prototypelist.remove(testlist[lengthtest])
if currentterm in prototypelist:
repititionfn=1
else:
repititionfn=0
if repititionfn==0 and occurences>1:
try:
finalizedtermsfn.append(str(currentterm)+"("+str(occurences)+")")
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
except:
print("Fail")
del finalizedtermsfn[-1]
elif repititionfn==0 and occurences==1:
try:
finalizedtermsfn.append(str(prototypelist[lengthtest]))
repititionfn=1
occurences=0
currentterm=prototypelist[lengthtest]
except:
print("Fail")
else:
currentterm=prototypelist[lengthtest]
return(finalizedtermsfn)
a=[6,0,1,1,1,1,1,2,2,2,2,4,4,4,5,5]
print(refine(a))
这打印:
['5(2)','4(3)','2(4)','1(5)','6']
解决方案
您可以使用collections.Counter
列表推导:
a=[6,0,1,1,1,1,1,2,2,2,2,4,4,4,5,5]
from collections import Counter
print(["%s(%d)"%(k,v) for k, v in Counter(a).items()])
#['0(1)', '1(5)', '2(4)', '4(3)', '5(2)', '6(1)']
如果您想避免在单个项目的括号中打印 1,您可以执行以下操作:
print(["%s(%d)"%(k,v) if v > 1 else str(k) for k, v in Counter(a).items()])
#['0', '1(5)', '2(4)', '4(3)', '5(2)', '6']
推荐阅读
- c# - grpc客户端的证书认证问题
- java - 如何删除具有特定列号和行号的所有值?
- vue.js - Vue SSR 将 express 服务器与 vue 应用程序捆绑在一起,因此应用程序可以从复制到主机服务器的 build dist 文件夹中运行
- php - PHP MySQL HTML 新贴纸
- python - 适用于 Linux 和 Windows 的多线程键盘检测器
- python - 尝试执行将使用 df 中的某些列的循环,得到错误: KeyError: '[0 1 2 6 7] not in index'
- r - 使用 dplyr mutate_at 通过 case_when 语句更改指定的变量列表
- ios - 四舍五入货币值(SwiftUI、Core Data)
- reactjs - 从 Webview 获取和传递 React Native 中的变量
- spring-boot - 反向 tls 代理后面的 Primefaces 主题不适用