如果我想返回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]发布于 2022-05-05 18:45:01
将一组他需要的值直接传递给Counter,然后在list1上迭代以获得它们的计数或0
def matchingStrings(list1, list2):
counts = Counter(list1)
return [counts.get(value, 0) for value in list2]
print(matchingStrings(list1, list2)) # [1, 0, 0, 0, 0]Counter对list.count的基准测试
from collections import Counter, defaultdict
from datetime import datetime
import numpy as np
def matchingStrings(list1, list2):
counts = Counter(list1)
return [counts.get(value, 0) for value in list2]
def matchingStrings2(list1, list2):
return [list1.count(a) for a in list2]
if __name__ == '__main__':
nb = 5000
times = defaultdict(list)
for i in range(10):
list1 = list(np.random.randint(0, 100, nb))
list2 = list(np.random.randint(0, 100, nb))
s = datetime.now()
x1 = matchingStrings(list1, list2)
times["counter"].append(datetime.now() - s)
s = datetime.now()
x2 = matchingStrings2(list1, list2)
times["list"].append(datetime.now() - s)
print(np.mean(times['list']) / np.mean(times['counter']))
for key, values in times.items():
print(f"{key:7s} => {np.mean(values)}")Counter解决方案的复杂性是2n,而list.count解决方案是n²
这里有几个数字
nb = 1000 # lists size
39.18844022169438 # counter 50 times faster
counter => 0:00:00.001263
list => 0:00:00.049495
nb = 5000 # lists size
481.512173128945 # counter 500 times faster
counter => 0:00:00.003327
list => 0:00:01.601991
nb = 10000 # lists size
1104.0679151061174 # counter 1000 times faster
counter => 0:00:00.004005
list => 0:00:04.421792发布于 2022-05-05 18:47:10
一个小小的修正可以解决以下问题:
from collections import Counter
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
def matchingStrings(list1, list2):
count_all=Counter(list2)
counts= {x: count_all[x] for x in list1 }
list_output=list(counts.values())
print(list_output)
return list_output
# Write your code here
if __name__ == '__main__':
matchingStrings(list1,list2)发布于 2022-05-05 18:41:54
尝试使用count方法。
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
def matchingStrings(list1, list2):
new_list = [list1.count(a) for a in list2]
print(new_list)
return new_list
if __name__ == '__main__':
matchingStrings(list1,list2)产出:
[1, 0, 0, 0, 0]https://stackoverflow.com/questions/72132148
复制相似问题