我有一本這樣的字典:
dict = {
key1: <http://www.link1.org/abc/f><http://www.anotherlink.com/ght/y2>,
key2: <http://www.link1.org/abc/f><http://www.anotherOneLink.en/ttta/6jk>,
key3: <http://www.somenewlink.xxw/o192/ggh><http://www.link4.com/jklu/wepdo9>,
key4: <http://www.linkkk33.com/fgkjc><http://www.linknew2.com/poii/334hsj>,
...
}
目標實作:
我想將字典每個值內的 2 個鏈接分開,然后計算每個第一個值在整個字典中出現的次數。是這樣的:
new_dict = {
key1: [<http://www.link1.org/abc/f>, <http://www.anotherlink.com/ght/y2>],
key2: [<http://www.link1.org/abc/f>, <http://www.anotherOneLink.en/ttta/6jk>],
key3: [<http://www.somenewlink.xxw/o192/ggh>, <http://www.link4.com/jklu/wepdo9>],
key4: [<http://www.linkkk33.com/fgkjc>, <http://www.linknew2.com/poii/334hsj>],
...
}
first_value_count = {
<http://www.link1.org/abc/f> : 2,
<http://www.somenewlink.xxw/o192/ggh> : 1,
<http://www.linkkk33.com/fgkjc> : 1,
....
}
我的代碼:
為了拆分我試過的值,但它不起作用:
new_dict = {k: v[0].split(">") for k, v in dict.items()}
要計算我的字典中的值出現次數:
from collections import Counter
all_dictionary_values = []
for v[0] in new_dict.values():
all_dictionary_values.append(x)
count = Counter(all_dictionary_values)
我有一個非常大的字典(超過 100 萬個鍵),這是計算字典中所有值出現次數的最快方法嗎?
uj5u.com熱心網友回復:
我試過你的代碼,但它對我不起作用,所以我改變了它如下:
dict = {
'key1' : "<http://www.link1.org/abc/f><http://www.anotherlink.com/ght/y2>",
'key2': "<http://www.link1.org/abc/f><http://www.anotherOneLink.en/ttta/6jk>",
'key3' : "<http://www.somenewlink.xxw/o192/ggh><http://www.link4.com/jklu/wepdo9>",
'key4': "<http://www.linkkk33.com/fgkjc><http://www.linknew2.com/poii/334hsj>",
}
new_dict = {k: v.split("><") for k, v in dict.items()}
new_dict
輸出
{'key1': ['<http://www.link1.org/abc/f', 'http://www.anotherlink.com/ght/y2>'],
'key2': ['<http://www.link1.org/abc/f',
'http://www.anotherOneLink.en/ttta/6jk>'],
'key3': ['<http://www.somenewlink.xxw/o192/ggh',
'http://www.link4.com/jklu/wepdo9>'],
'key4': ['<http://www.linkkk33.com/fgkjc',
'http://www.linknew2.com/poii/334hsj>']}
我們在這里添加計數器:
from collections import Counter
all_dictionary_values = []
for v in new_dict.values():
all_dictionary_values.append(v[0] ">")
count = Counter(all_dictionary_values)
count
輸出
Counter({'<http://www.link1.org/abc/f': 2,
'<http://www.somenewlink.xxw/o192/ggh': 1,
'<http://www.linkkk33.com/fgkjc': 1})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535003.html
