如下兩個串列串列,它需要找出子串列中每個元素對的次數(計數)。
例如,William_Delta 出現了 4 次。
結果要寫入txt檔案。
processes = [['Iota', 'Gamma', 'Kappa'], ['Delta', 'Zeta', 'Beta'], ['Alpha', 'Zeta'], ['Alpha', 'Epsilon', 'Delta', 'Beta']]
staffs = [['William', 'James', 'Noah', 'Oliver'], ['Benjamin', 'Oliver', 'William'],['Oliver', 'Benjamin']]
list_output = []
for each_p in processes:
for p in each_p:
for each_s in staffs:
for s in each_s:
output = s '_' p
list_output.append(output)
uniques = set(list_output)
with open('c:\\temp\\outfile.txt', 'a') as outfile:
for ox in uniques:
outfile.write(ox '@' str(list_output.count(ox)) "\n")
“流程”和“人員”的長度都非常長,因此需要很多時間才能完成。
縮短跑步時間的更好方法是什么?
謝謝你。
uj5u.com熱心網友回復:
使用collections.Counter每一個元素出現在每個子表計時,然后用itertools.product找出所有對。最后,總計數是每個計數的乘積。例如,"William"出現 2 次,"Delta"出現 2 次,因此該對的總數"William_Delta"為 4 (2 * 2)。
from collections import Counter
from itertools import product
processes = [['Iota', 'Gamma', 'Kappa'], ['Delta', 'Zeta', 'Beta'], ['Alpha', 'Zeta'], ['Alpha', 'Epsilon', 'Delta', 'Beta']]
staffs = [['William', 'James', 'Noah', 'Oliver'], ['Benjamin', 'Oliver', 'William'],['Oliver', 'Benjamin']]
count_staffs = Counter(st for staff in staffs for st in staff)
count_processes = Counter(pr for process in processes for pr in process)
with open('outfile.txt', 'a') as outfile:
for (staff, cs), (process, cp) in product(count_staffs.items(), count_processes.items()):
outfile.write(f"{staff}_{process}@{cs * cp}\n")
這個解決方案應該比找到所有對并計算它們更快。
uj5u.com熱心網友回復:
您可以使用collections.Counterandchain.from_iterable和productfrom itertools:
from collections import Counter
from itertools import product, chain
output = Counter(
f"{s}_{p}" for p, s in
product(*map(chain.from_iterable, [processes, staffs]))
)
with open(file) as outfile:
for name, count in output.items():
outfile.write(f"{name}@{count}\n")
更詳細的版本是:
all_processes = chain.from_iterable(processes)
all_staffs = chain.from_iterable(staffs)
name_counts = Counter(f"{s}_{p}" for s, p in product(all_processes, all_staffs))
with open(file) as outfile:
for name, count in name_counts.items():
outfile.write(f"{name}@{count}\n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358407.html
上一篇:避免回圈中的條件陳述句
