简体   繁体   English

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

[英]How to do list comprehension on a list of dictionaries without returning values in a list?

I'm trying to perform list comprehension on a list of dictionaries.我正在尝试对字典列表执行列表理解。 Using an example I found here , works, but returns a list of lists.使用我在此处找到的示例可以正常工作,但会返回列表列表。 This is the code I am using:这是我正在使用的代码:

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

Which would return a list as such: [['deposit'], ['withdrawal'], ['withdrawal'], ['withdrawal'], ['deposit'], ['closed account']]这将返回一个列表:[['deposit'], ['withdrawal'], ['withdrawal'], ['withdrawal'], ['deposit'], ['close account']]

How can I do the same, but without returning the values inside of a list?我怎样才能做同样的事情,但不返回列表中的值? The result would look like so: ['deposit', 'withdrawal', 'withdrawal', 'withdrawal', 'deposit', 'closed account'].结果看起来像这样:['deposit', 'withdrawal', 'withdrawal', 'withdrawal', 'deposit', 'close account']。

Dropping the list inside of the list comprehension like so:像这样在列表理解中删除列表:

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

just returns the first value of the dictionary * the number of dictionaries.只返回字典的第一个值 * 字典的数量。 Eg : [['deposit'], ['deposit'], ['deposit'], ['deposit'], ['deposit'], ['deposit']]例如:[['deposit']、['deposit']、['deposit']、['deposit']、['deposit']、['deposit']]

Using technique from: How to convert a nested loop to a list comprehension in python we have the following two equivalent solutions.使用来自: 如何在 python 中将嵌套循环转换为列表理解的技术,我们有以下两个等效的解决方案。

List Comprehension列表理解

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

Double For Loop双循环

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