我正在一个项目上,令人讨厌的是,当我打印列表时,例如('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']
答案 0 :(得分:3)
您可以将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']