有没有办法在python中“堆叠”列表?

2024-09-28 05:43:39 发布

您现在位置: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']


Tags: andlenifelseprintwhilestrrefine
1条回答
网友
1楼 · 发布于 2024-09-28 05:43:39

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

相关问题 更多 >

    热门问题