反转键/值对

时间:2021-06-21 06:46:45

标签: python list dictionary counter

我编写了以下代码:

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

提前致谢

1 个答案:

答案 0 :(得分:0)

感谢@oskros

修改后的最终代码:

from collections import Counter

shopping_list = input().split()
a = Counter(shopping_list)

print('\n'.join("{} {}".format(v, k) for k, v in a.items()))
相关问题