大家好,我是 python 的初學者,正在做一些示例練習并學習使用字典。我提供了以下串列,并嘗試使用重復的 understudy_num 獲得以下輸出。
cast_list = [{'actor_id' : 98109, 'understudy_num' : 756},
{'actor_id' : 82793, 'understudy_num' : 392},
{'actor_id' : 71290, 'understudy_num' : 128},
{'actor_id' : 71290, 'understudy_num' : 407},
{'actor_id' : 98109, 'understudy_num' : 898}, ]
98109 : [759, 898]
82793 : [392]
71290 : [128, 407]
首先,我這樣做并得到了結果
for key in cast_list :
print(key['actor_id'], ':', key['understudy_num'])
98109 : 756
82793 : 392
71290 : 128
71290 : 407
98109 : 898
現在我對如何將 actor_id 獲取給相應的替補感到困惑?我開始了
#print("GIVEN:" , cast_list ) #just to print original
new_list= []
for key in cast_list:
if key['actor_id'] not in new_list:
new_list[key['actor_id']] = [key]
else:
new_list[key['understudy_num']].apend(key)
print(key['actor_id'], ':', '[', key['understudy_num'] , ']')
ERROR: list assignment index out of range
我的邏輯:我們想查看 cast_list 中的鍵和值...如果 actor_id 不在串列中,請將其作為鍵添加到 new_list 中,否則(如果鍵已經在 new_list 中)附加適當的鍵與值。
更清晰的邏輯嘗試。
new_list= []
for dict in cast_list:
for key,value in dict.items():
if key in new_list.keys():
new_list[key].append(value)
else:
new_list[key]=[value]
print(new_list)
AttributeError: 'list' object has no attribute 'keys'
關于從這里去哪里的任何提示/鏈接/解決方案?我也有幾次錯誤說TypeError: list indices must be integers or slices, not str但我認為我的串列已經是整數了?
uj5u.com熱心網友回復:
你真的很親近!您的邏輯是合理的,您只是在混淆如何使用不同的資料結構:
- 串列是有序專案(值)的序列,沒有關聯的鍵。
- 字典是鍵值對的無序集合。
在這里,您希望將一個鍵(您的actor)與多個值(您的understudies)相關聯。為了實作你想要的最好的方法是創建一個字典:
new_dict = {}
for d in cast_list:
actor = d["actor_id"]
understudy = d["understudy_num"]
if actor not in new_dict:
new_dict[actor] = [understudy]
else:
new_dict[actor].append(understudy)
示例輸出:
>>> for k, v in new_dict.items():
... print(k, ":", v)
...
98109 : [756, 898]
82793 : [392]
71290 : [128, 407]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/414405.html
標籤:
上一篇:從python串列中獲取具有兩列的pandas資料框
下一篇:如何將嵌套集轉換為串列?
