比较2个列表并返回List2中存在的List1元素中的事件计数后返回列表2
如果我想返回list1
中的值的列表与list2
相比,该怎么办?
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
我期望0出现1,0发生2,0发生3,0发生4,1出现5;要拥有下面的新列表,
new_list = [1, 0, 0, 0, 0]
请参见下文。我在做什么错?
from collections import Counter
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
def matchingStrings(list1, list2):
count_all=Counter(list1)
counts= {x: count_all[x] for x in list2 if x in list1 }
list_output=list(counts.values())
print(list_output)
return list_output
# Write your code here
if __name__ == '__main__':
matchingStrings(list1,list2)
输出
预期输出
[1, 0, 0, 0, 0]
What if I want to return the list of occurrence of the values in list1
as compared to list2
as below?
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
I expect to get 0 occurrence of 1, 0 occurrence of 2, 0 occurrence of 3, 0 occurrence of 4, and 1 occurrence of 5; to have a new list as below,
new_list = [1, 0, 0, 0, 0]
See below by implementation. What am I doing wrong?
from collections import Counter
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
def matchingStrings(list1, list2):
count_all=Counter(list1)
counts= {x: count_all[x] for x in list2 if x in list1 }
list_output=list(counts.values())
print(list_output)
return list_output
# Write your code here
if __name__ == '__main__':
matchingStrings(list1,list2)
Output
Expected output
[1, 0, 0, 0, 0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
直接将一组需要值传递给
counter
然后在list1
上迭代以获取其计数或0基准的
Counter> Counter
vslist.count
计数器
解决方案的复杂性是2n
,而list.count.count
解决方案是n²
这是一个几个数字
Directly pass a set of he needed values to the
Counter
then iterate on thelist1
to get their count or 0Benchmark of
Counter
vslist.count
Complexity of
Counter
solution is2n
whereaslist.count
solution isn²
Here's a few numbers
一个小的更正修复了:
A small correction fixes that:
尝试使用
Count
方法。输出:
Try using the
count
method.OUTPUT: