【发布时间】:2022-01-13 12:20:24
【问题描述】:
我正在尝试对字典列表执行列表理解。使用我找到的here 的示例,它可以工作,但会返回一个列表列表。这是我正在使用的代码:
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].
只返回字典的第一个值 * 字典的数量。例如。 : [['定金']、['定金']、['定金']、['定金']、['定金']、['定金']]
【问题讨论】:
-
使用普通循环并追加到列表中。
-
我认为你可以使用“get”和一个额外的参数来处理 key-not-found 的情况。
-
@MarkLavin 你能举出任何例子吗?
-
你能举出字典 t 的例子吗?
-
“像这样在列表理解中删除列表”--transaction_type 与原始表达式有何不同?试试
transaction_types=[v for t in all_transactions for k,v in t.items() if 'transaction_type' in k]
标签: python list dictionary