1 回答

TA貢獻1789條經驗 獲得超8個贊
更新:意識到OP的文本正在處理非唯一的查找。添加了一段來描述如何做到這一點。
如果您發現自己多次循環字典列表來執行查找,請將列表重組為字典,以便查找成為鍵。例如這個:
a = [{"id": 1, "value": "foo"}, {"id": 2, "value": "bar"}]
for item in a:
if item["id"] == 1:
print(item["value"])
可以變成這樣:
a = [{"id": 1, "value": "foo"}, {"id": 2, "value": "bar"}]
a = {item["id"]: item for item in a} # index by lookup field
print(a[1]["value"]) # no loop
... # Now we can continue to loopup by id eg a[2] without a loop
如果它是非唯一查找,您可以執行類似的操作:
indexed = {}
a = [{"category": 1, "value": "foo"}, {"category": 2, "value": "bar"}, {"category": 1, "value": "baz"}]
for item in a: # This loop only has to be executed once
if indexed.get(item["category"], None) is not None:
indexed[item["category"]].append(item)
else:
indexed[item["category"]] = [item]
# Now we can do:
all_category_1_data = indexed[1]
all_category_2_data = indexed[2]
如果出現索引錯誤,請使用默認字典索引來更輕松地處理
if a.get(1, None) is not None:
print(a[1]["value"])
else:
print("1 was not in the dictionary")
在我看來,這個 API 沒有任何“Pythonic”,但如果 API 返回您需要循環的列表,那么它可能是一個設計糟糕的 API
更新:好的,我會嘗試修復您的代碼:
def download_vid(topics_data, ydl_opts):
indexed_data = {'reddit': [], 'gfycat': [], 'thumbnail': []}
for item in topics_data['vid']:
if item.get('reddit_video', None) is not None:
indexed_data['reddit'].append(item)
elif item.get('type', None) == "gfycat.com":
indexed_data['gfycat'].append(item)
elif item.get('oembed', None) is not None:
if item['oembed'].get('thumbnail_url', None) is not None:
indexed_data['thumbnail'].append(item)
for k, v in indexed_data.items():
assert k in ('reddit_video', 'gfycat', 'thumbnail')
if k == 'reddit_video':
B = v['reddit_video']['fallback_rul']
...
elif k == 'gfycat':
C = v['oembed']['thumbnail_url']
...
elif k == 'thumbnail':
D = v['oembed']['thumbnail_url']
...
以防萬一不清楚為什么這樣更好:
OP 循環了 topic_data['vid'] 3 次。我做了兩次。
更重要的是,如果加更多的題目,我仍然只做兩次。OP將不得不再次循環。
無異常處理。
現在每組對象都已編入索引。所以OP可以做,例如indexed_data['gfycat']來獲取所有這些對象(如果需要的話),這是一個哈希表查找,所以它很快
添加回答
舉報