如果我有一個如下所示的串列:
['1 184',
'1 29',
'1 31',
'1 12',
'1 51',
'1 102',
'1 13',
'1 14',
'1 15',
'1 57',
'1 378',
'1 859',
'1 185',
'1 30',
'1 37',
'1 52',
'1 142',
'1 195',
'1 875',
'1 56',
'1 66',
'1 95',
'1 462',
'1 497',
'1 858',
'1 876',
'1 879',
'1 880',
'2 12',
'2 15',
'2 184',
'2 858',
'2 51']
我想將每個字串的第一個元素映射到與第一個數字相關的每個下一個元素,并以{1 : [184, 29, 31...], 2 : [12, 15, 18, ...]}
.
我怎么能那樣做?
uj5u.com熱心網友回復:
如果lst
是您的問題串列,那么:
out = {}
for a, b in map(str.split, lst):
out.setdefault(int(a), []).append(int(b))
print(out)
印刷:
{
1: [
184,
29,
31,
12,
51,
102,
13,
14,
15,
57,
378,
859,
185,
30,
37,
52,
142,
195,
875,
56,
66,
95,
462,
497,
858,
876,
879,
880,
],
2: [12, 15, 184, 858, 51],
}
編輯:要明確檢查正確的值:
out = {}
for value in lst:
value = value.split()
if len(value) == 2:
a, b = value
out.setdefault(int(a), []).append(int(b))
uj5u.com熱心網友回復:
我想我理解你的問題。這能解決嗎?
Dictionary = dict() # You must use `dict()` for an empty dictionary because if you write "{}", Python will think it's a set
# Loop through each value in `x`
for Value in x:
# Get the Key and Value for the Dictionary
Key,Value = Value.split(" ")
# If the dictionary's value at key: `Key` has not been set, it will raise a KeyError once called. If this is the case, you must create a blank list for the Value in `Key`
try:
Dictionary[Key]
except KeyError:
Dictionary[Key] = []
# Add the Value to the Dictionary at `Key`
Dictionary[Key].append(Value)
注意:x
是list()
在問題中
uj5u.com熱心網友回復:
另一種可能的解決方案,基于熊貓資料框的創建:
(pd.DataFrame
.from_records([list(map(int, x.split())) for x in l], columns=list('ab'))
.groupby('a')['b'].apply(list).to_dict())
輸出:
{1: [184, 29, 31, 12, 51, 102, 13, 14, 15, 57, 378, 859, 185, 30, 37,
52, 142, 195, 875, 56, 66, 95, 462, 497, 858, 876, 879, 880],
2: [12, 15, 184, 858, 51]}
uj5u.com熱心網友回復:
我只會使用defauldict
帶有list
值的
from collections import defaultdict
res = defaultdict(list)
for item in data:
k, v = item.split()
res[int(k)].append(int(v))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505280.html
上一篇:熊貓從for回圈創建csv檔案