目前,我有一个列表,其中包含:
lst = [[2],[2,2],[2,2,2,3,3],[2,3,5,5]]
我正在尝试以下面的格式打印:
2^1 #since there is only one '2'
2^2 #since there are two '2' in the first list
2^3 | 3^2 #three '2' and two '3'
2^1 | 3^1 | 5^2 #one '2', one '3' and two '5'
我尝试过:
for i in range(len(lst)):
count = 1
if len(lst[i]) == 1:
print(str(lst[i][0]) + "^" + str(count))
else:
for j in range(len(lst[i])-1):
if lst[i][j] == lst[i][j+1]:
count+=1
else:
print(str(lst[i][j]) + "^" + str(count) + " | " +str(lst[i][j+1]) + "^" +str(count))
if count == len(lst[i]):
print(str(lst[i][j]) + "^" + str(count))
但是我得到了输出
2^1
2^2
2^3 | 3^3
2^1 | 3^1
3^1 | 5^1
希望得到一些帮助
最佳答案
使用 itertools.Counter
的简单变体
from collections import Counter
for sublist in lst:
c = Counter(sublist)
print(' | '.join(f'{number}^{mult}' for number, mult in c.items()))
这可以让计数器
完成计数工作并仅以您所需的格式显示项目。
Counter
对象的工作方式类似于字典,如下所示(列表中的最后一项):
c = Counter({5: 2, 2: 1, 3: 1})
与dict
一样,您可以使用c.items()
迭代键,值
对。格式字符串 f'{number}^{mult}'
然后生成类似 5^2
的字符串,然后是 join
ed 使用分隔符 ' | '
。
关于python - 根据元素在列表中出现的次数打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52723177/