[英]Delete a dictionary item based on a value from a list iteration
我嘗試了以下方法:
losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
del candidates_and_fp_votes[losers[i]]
print(candidates_and_fp_votes)
這只會返回錯誤:
TypeError:列表索引必須是整數或切片,而不是str
我想遍歷失敗者和刪除每個項目candidates_and_fp_votes
其中有一個關鍵的losers
我期望輸出:
{'a': 24, 'c': 17, 'd': 23}
我怎么解決這個問題?
提前致謝。
i
是列表元素,而不是索引。 它應該是:
del candidates_and_fp_votes[i]
或者應該是:
for i in in range(len(losers)):
如果您確實出於某種原因想要索引。
當您遍歷對象(在本例中為“失敗者”的列表)時,變量i
實際上是對象中的數據,而不是您在其他語言(c / c ++)中可能看到的數據索引。 因此,在for循環的第一次迭代中, i == 'e'
然后在第二次i == 'b'
則循環將結束,因為沒有更多數據。
因此,您要做的就是將失敗者[i]更改為i:
del candidates_and_fp_votes[i]
這是固定行的完整代碼。
losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
del candidates_and_fp_votes[i]
print(candidates_and_fp_votes)
您的索引i
是一個字符串,而不是整數。 您可以執行以下操作:
losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
for i in losers:
if i in candidates_and_fp_votes:
del candidates_and_fp_votes[i]
print(candidates_and_fp_votes)
您可以使用字典理解:
losers = ['e', 'b']
candidates_and_fp_votes = {'a': 24, 'b': 0, 'c': 17, 'd': 23, 'e': 0}
final_dict = {a:b for a, b in candidates_and_fp_votes.items() if a not in losers}
輸出:
{'a': 24, 'c': 17, 'd': 23}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.