繁体   English   中英

如何在不返回列表中的值的情况下对字典列表进行列表理解?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM