【发布时间】:2021-09-04 20:40:23
【问题描述】:
我写了以下代码:
from collections import Counter
shopping_list = input().split()
a = Counter(shopping_list)
print('\n'.join("{} {}".format(k, v) for k, v in a.items()))
如果输入是carrots carrots bread tomatoes onions apples tomatoes carrots tomatoes onions onions onions bread milk bread apples
代码输出:
carrots 3
bread 3
tomatoes 3
onions 4
apples 2
milk 1
代码工作正常,但任何插入输入的对都必须在项目本身之前使用计数器打印。 (测试环境每次都会插入不同的输入)
那么我如何让它像这样输出呢?
3 carrots
3 bread
3 tomatoes
4 onions
2 apples
1 milk
提前致谢
【问题讨论】:
-
只需将
.format(k, v)更改为.format(v, k) -
不将 format(k,v) 反转为 format(v, k) 只是反转它?
-
是的,确实如此@TharakaDevinda
标签: python list dictionary counter