使用if / else语句的嵌套列表理解

时间:2019-10-09 19:13:26

标签: python list-comprehension

我觉得可以通过列表理解和基于相关答案的功能来改善此代码段。然后,我继续更改此代码段:

file.url

无法使用的新版本:

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)

哪些人由于语法错误而抱怨:

文件“”,第33行     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)                                        ^ SyntaxError:语法无效

1 个答案:

答案 0 :(得分:0)

我在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)