简体   繁体   English

列表对列表中嵌套的列表的理解

[英]List Comprehension of Lists Nested in Dictionaries

I have a dictionary where each value is a list, like so: 我有一个字典,其中每个值都是一个列表,如下所示:

dictA = {1:['a','b','c'],2:['d','e']}

Unfortunately, I cannot change this structure to get around my problem 不幸的是,我无法改变这种结构来解决我的问题

I want to gather all of the entries of the lists into one single list, as follows: 我想将列表的所有条目收集到一个列表中,如下所示:

['a','b','c','d','e']

Additionally, I want to do this only once within an if-block. 另外,我想在if-block中只执行一次。 Since I only want to do it once, I do not want to store it to an intermediate variable, so naturally, a list comprehension is the way to go. 由于我只想做一次,我不想将它存储到一个中间变量,所以自然地,列表理解是要走的路。 But how? 但是怎么样? My first guess, 我的第一个猜测,

[dictA[key] for key in dictA.keys()]

yields, 产量,

[['a','b','c'],['d','e']]

which does not work because 哪个不起作用,因为

'a' in  [['a','b','c'],['d','e']]

yields False . 收益False Everything else I've tried has used some sort of illegal syntax. 我尝试的其他所有内容都使用了某种非法语法。

How might I perform such a comprehension? 我怎么能表现出这样的理解力呢?

Loop over the returned list too (looping directly over a dictionary gives you keys as well): 循环遍历返回的列表(直接在字典上循环为您提供键):

[value for key in dictA for value in dictA[key]]

or more directly using dictA.itervalues() : 或更直接使用dictA.itervalues()

[value for lst in dictA.itervalues() for value in lst]

List comprehensions let you nest loops; 列表推导让你嵌套循环; read the above loops as if they are nested in the same order: 阅读上面的循环,好像它们以相同的顺序嵌套:

for lst in dictA.itervalues():
    for value in lst:
        # append value to the output list

Or use itertools.chain.from_iterable() : 或者使用itertools.chain.from_iterable()

from itertools import chain

list(chain.from_iterable(dictA.itervalues()))

The latter takes a sequence of sequences and lets you loop over them as if they were one big list. 后者采用一系列序列,让你循环遍历它们,好像它们是一个大的列表。 dictA.itervalues() gives you a sequence of lists, and chain() puts them together for list() to iterate over and build one big list out of them. dictA.itervalues()为您提供了一系列列表,并且chain()将它们放在一起以便list()迭代并构建一个大列表。

If all you are doing is testing for membership among all the values, then what you really want is to a simple way to loop over all the values, and testing your value against each until you find a match. 如果你所做的只是测试所有值中的成员资格,那么你真正想要的是一种简单的方法来遍历所有的值,并测试你的值,直到你找到匹配。 The any() function together with a suitable generator expression does just that: any()函数和合适的生成器表达式就是这样:

any('a' in lst for lst in dictA.itervalues())

This will return True as soon as any value in dictA has 'a' listed, and stop looping over .itervalues() early. 一旦dictA'a'任何值列出'a' ,就会返回True并且尽早停止循环.itervalues()

If you're actually checking for membership (your a in... example), you could rewrite it as: 如果您实际上正在检查成员身份(您的a in...示例),您可以将其重写为:

if any('a' in val for val in dictA.itervalues()):
    # do something

This saves having to flatten the list if that's not actually required. 如果实际上不需要,则可以节省必须压缩列表。

In this particular case, you can just use a nested comprehension: 在这种特殊情况下,您可以使用嵌套理解:

[value for key in dictA.keys() for value in dictA[key]]

But in general, if you've already figured out how to turn something into a nested list, you can flatten any nested iterable with chain.from_iterable : 但总的来说,如果你已经想出如何将某些东西变成嵌套列表,你可以使用chain.from_iterable来展平任何嵌套的iterable:

itertools.chain.from_iterable(dictA[key] for key in dictA.keys())

This returns an iterator, not a list; 这将返回一个迭代器,而不是一个列表; if you need a list, just do it explicitly: 如果您需要一个列表,请明确地执行:

list(itertools.chain.from_iterable(dictA[key] for key in dictA.keys()))

As a side note, for key in dictA.keys() does the same thing as for key in dictA , except that in older versions of Python, it will waste time and memory making an extra list of the keys. 作为旁注, for key in dictA.keys()中的for key in dictA相同的for key in dictA ,除了在旧版本的Python中,它会浪费时间和内存来创建一个额外的键列表。 As the documentation says, iter on a dict is the same as iterkeys . 正如文档所说, dict上的iteriterkeys相同。

So, in all of the versions above, it's better to just use in dictA instead. 所以,在上面的所有版本中,最好只in dictA使用。

In simple code just for understanding this might be helpful 在简单的代码中只是为了理解这可能会有所帮助

ListA=[]
dictA = {1:['a','b','c'],2:['d','e']}
for keys in dictA:
    for values in dictA[keys]:
        ListA.append(values)

You can do some like .. 你可以做一些像..

output_list = []

[ output_list.extend(x) for x in {1:['a','b','c'],2:['d','e']}.values()]

output_list will be ['a', 'b', 'c', 'd', 'e'] output_list将是['a','b','c','d','e']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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