[英]How to count how many times a number is repeated in a list( and if a number is not used based on values from another list )?
I have two lists : 我有两个清单:
list1 = [1,2,3]
list2= [1,1,2,2,2]
Is there a way to print how many times a number in list1 has occurred in list2/ or if a number hasn't appeared in the list2, then say 0. 有没有一种方法可以打印列表2中的一个数字出现在列表1中的次数,或者如果列表2中没有出现数字,则说0。
i tried using: 我尝试使用:
Counter(list2)
but this gives me the output: 但这给了我输出:
{2: 3, 1: 2}
the outcome I want is: 我想要的结果是:
{1: 2, 2: 3, 3:0}
When I use counter it doesn't say how many 3's are seen in list2. 当我使用计数器时,它不会说在list2中看到了3个。 is there a simple way around this problem?
有没有解决此问题的简单方法?
You need to iterate list1 and then give reference to list2 您需要迭代list1,然后引用list2
>>> {i: list2.count(i) for i in list1}
{1: 2, 2: 3, 3: 0}
Use simple for loop 使用简单的for循环
list1 = [1,2,3]
list2= [1,1,2,2,2]
dict = {}
count = 0
for num1 in list1:
for num2 in list2:
if num1 == num2:
count = count +1
dict[num1] = count
count = 0
print(dict)
output 产量
{1: 2, 2: 3, 3:0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.