简体   繁体   English

python嵌套列表理解中的if else逻辑

[英]If else logic in python nested list comprehension

I have a list which could consist of either lists or integers or None. 我有一个列表,可以由列表或整数或无组成。 I want to flatten the iterable elements (assuming only lists for now) inside this list to individual elements. 我想将此列表内的可迭代元素(现在仅假设列表)展平为单个元素。

for eg: 例如:

[[0, 1], [2, 3], 1, 3, 4, 0, None] into [0,1,2,3,1,3,4,0,None] 

using list comprehension. 使用列表理解。 I found another similar question but all those elements were iterable in that list, since mine has integers too how do I use if else logic in the list comprehension for the first "for loop". 我发现了另一个类似的问题,但是所有这些元素在该列表中都是可迭代的,因为我的也有整数,如果列表理解第一个“ for循环”中的逻辑,我也应该使用整数。 I am trying something like this, but not sure what the exact syntax is to flatten out. 我正在尝试类似的方法,但不确定确切的语法是什么。

[ item sublist if isinstance(sublist,list) else [sublist] for sublist in A for item in sublist ] [如果为isinstance(sublist,list),则为项目子列表,否则为A中的子列表的[sublist]为子列表中的项目]

Based on other questions, if-else should occur prior to for loops and for loops have to occur in order. 基于其他问题,if-else应该在for循环之前发生,并且for循环必须按顺序发生。 I am unable to insert if else after the first for loop, syntax allows only if and not else. 我无法在第一个for循环后插入if,否则语法只能在if时插入,否则不能插入。

Could someone help with syntax of this please, for doing if-else on the first for loop or any intermediate for loop in nested for loops in comprehension? 有人可以帮忙解决一下这个语法,以便在理解的第一个for循环或嵌套的for循环中的任何中间for循环上执行if-else吗?

You can use a generator to convert your mixed list into an iterable that only has lists: 您可以使用生成器将混合列表转换为仅包含列表的可迭代对象:

gen = (x if isinstance(x, collections.Iterable) else [x] for x in A)

Then you can use the standard flattening idiom to flatten out the generator: 然后,您可以使用标准的拼合习惯来拼合生成器:

flattened = [y for x in gen for y in x]

@mgilson gave an elegant solution using a comprehension. @mgilson使用理解力给出了一种优雅的解决方案。 It is also possible to do so in a natural loop using error-trapping: 也可以使用错误捕获在自然循环中这样做:

items = [[0, 1], [2, 3], 1, 3, 4, 0, None]
flattened = []
for item in items:
    try:
        flattened.extend(item)
    except TypeError:
        flattened.append(item)

print(flattened) #prints [0, 1, 2, 3, 1, 3, 4, 0, None]

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

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