首页 > 解决方案 > 有没有办法在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']

标签: python

解决方案


您可以使用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']

推荐阅读