将多行循环更改为单行循环

时间:2018-10-02 01:09:06

标签: python loops for-loop

这是通过for循环添加到列表的一种方法:

lst = [] 
for i in range(5):
    lst.append(i)

尽管下面的内容看起来更好,更好:

lst = [i for i in range(5)]

我试图用下面的代码编写与第二种格式相同的代码,但是我一直遇到错误。有人可以帮忙吗?

filtered_list = []
for childList in source_list:
    filtered_childList = remove_emptyElements(childList)    
    if filtered_childList:   
         filtered_list.append(filtered_childList)

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

# one liner as you asked:
filtered_list = [remove_emptyElements(l) for l in source_list if remove_emptyElements(l)]

# but I think that this will be better:
filtered_list = (remove_emptyElements(l) for l in source_list)
filtered_list = [l for l in filtered_list if l]

更新: 要通过注释解决您的问题,您可以使用以下代码段:

sequences_result = []
for sequence in sequences:
    for itemset in sequence:
        itemset_result = []
        for item in itemset.split(","):
            itemset_result.append(item.strip())
        sequences_result.append(itemset_result)
print(sequences_result)