我需要在列表中仅打印重复的数字,并且需要乘以计数。代码如下,输出应该是,
{1:3:2:2,3:2}需要将每个数字乘以计数并打印为单独的答案:
answer1 = 1*3, answer2 = 2*2 , answer3 = 3*2
目前的尝试:
from collections import Counter
alist = [1,2,3,5,1,2,1,3,1,2]
a = dict(Counter(a_list))
print(a)
答案 0 :(得分:0)
Counter
已经完成了繁重的工作。那么对于其余部分,如何生成不止一次出现的值列表,根据需要格式化输出? (排序键似乎是必要的,因此索引匹配键顺序):
from collections import Counter
a_list = [1,2,3,5,1,2,1,3,1,2]
a = ["{}*{}".format(k,v) for k,v in sorted(Counter(a_list).items()) if v > 1]
print(a)
结果:
['1*4', '2*3', '3*2']
如果您想要数字结果:
a = [k*v for k,v in sorted(Counter(a_list).items()) if v > 1]
结果(可能更有用):
[4, 6, 6]
分配给单独的变量(answer1,answer2,answer3 = a
)并不是一个好主意。保留已编入索引的list