python - 根据元素在列表中出现的次数打印输出

标签 python

目前,我有一个列表,其中包含:

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/

相关文章:

python - Flask-SQLAlchemy 更新正在 MySQL 中创建新记录

python - 我无法使用 pygame.get_pressed() 读取键盘的状态

python - 简单的 Python 战舰游戏

python - 获取与同一个表中的父元素相关的子元素

python - Django 绝对 url

python - Flask-Migrate 在表修改时挂起

Python tornado redis - 如何做一个管道

python - 创建超链接以通过 python 访问多个 Excel 工作表

python - Python 中的缩进并不总是必要的?

python - 为什么 python 不需要 python 的类型声明,其他方式是什么 adv。不声明类型?