简体   繁体   English

带有 if/else 语句的嵌套列表理解

[英]nested list comprehension with if/else statement

I have the impression this snippet can be improved with list comprehension and a function based on the answers related.我的印象是这个片段可以通过列表理解和基于相关答案的 function 来改进。 Then, I proceeded to changed this snippet:然后,我开始更改此代码段:

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]
flat_list = []
for sublist in l:
    print("sublist: ", sublist)
    for item in sublist:
        if type(item)== list:
            for i in item:
                flat_list.append(i)
        else:
            flat_list.append(item)

print(flat_list)

To this new version which is not working:对于这个不起作用的新版本:

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]

def foo(item):
    flat_l=[]
    if type(item)== list:
        for i in item:
            flat_l.append(i)
    else:
        flat_l.append(item)

    return flat_l

flat_list=[item for sublist in l foo(item) for item in sublist]

print(flat_list)

Which is complaining due to syntax error:由于语法错误而抱怨:

File "", line 33 flat_list=[item for sublist in l foo(item) for item in sublist] ^ SyntaxError: invalid syntax文件“”,第 33 行flat_list=[item for sublist in l foo(item) for item in sublist] ^ SyntaxError: invalid syntax

my code in python3我在 python3 中的代码

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]
e=[]
any(e.extend(i[0]) if isinstance(i[0], list) else e.extend(i) for i in l)
print(e)

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

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