【问题标题】:How to do list comprehension on a list of dictionaries without returning values in a list?如何在不返回列表中的值的情况下对字典列表进行列表理解?
【发布时间】: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


【解决方案1】:

使用来自:How to convert a nested loop to a list comprehension in python 的技术,我们有以下两个等效的解决方案。

列表理解

 transaction_types=[v for t in all_transactions for k,v in t.items() if 'transaction_type' in k]

双 For 循环

transaction_types = []
for t in all_transactions:
    for k, v in t.items():
        if 'transaction_type' in k:
            transaction_types.append(v)

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2019-07-09
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2019-09-20
    • 1970-01-01
    相关资源
    最近更新 更多