如果我想回傳與下面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]
uj5u.com熱心網友回復:
直接將一組他需要的值傳遞給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]
Countervs的基準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解決方案是n2
這里有幾個數字
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
uj5u.com熱心網友回復:
一個小的更正修復了:
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)
uj5u.com熱心網友回復:
嘗試使用該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://www.uj5u.com/yidong/471201.html
下一篇:數字和問題的最優解
