![](/img/trans.png)
[英]Why is this dictionary comprehension for list of dictionaries not returning values?
[英]How to do list comprehension on a list of dictionaries without returning values in a list?
我正在嘗試對字典列表執行列表理解。 使用我在此處找到的示例可以正常工作,但會返回列表列表。 這是我正在使用的代碼:
transaction_types=[[v for k,v in t.items() if 'transaction_type' in k] for t in all_transactions].
這將返回一個列表:[['deposit'], ['withdrawal'], ['withdrawal'], ['withdrawal'], ['deposit'], ['close account']]
我怎樣才能做同樣的事情,但不返回列表中的值? 結果看起來像這樣:['deposit', 'withdrawal', 'withdrawal', 'withdrawal', 'deposit', 'close account']。
像這樣在列表理解中刪除列表:
transaction_types=[[v for k,v in t.items() if 'transaction_type' in k] for t in all_transactions].
只返回字典的第一個值 * 字典的數量。 例如:[['deposit']、['deposit']、['deposit']、['deposit']、['deposit']、['deposit']]
使用來自: 如何在 python 中將嵌套循環轉換為列表理解的技術,我們有以下兩個等效的解決方案。
列表理解
transaction_types=[v for t in all_transactions for k,v in t.items() if 'transaction_type' in k]
雙循環
transaction_types = []
for t in all_transactions:
for k, v in t.items():
if 'transaction_type' in k:
transaction_types.append(v)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.