python - 使用迭代和集合重写列表(根据条件删除条目)

标签 python list python-3.x iteration

如果任何子元素为空,我正在尝试删除列表中的元素(该列表目前为七维)。即给出这个更简单的示例列表:

'car','doug','' 
dede,eli,fred 
'law', '','frank' 
'','roger','w'
alex,berk,carl

删除任何带有“空白”(或某个时候的其他条件)的行后

dede,eli,fred
alex,berk, carl

到目前为止,我已经为我的列表做了一些事情(它有效!),该列表有 7 个使用集合的元素

list1=[item for item in list1 if item [0]!= '']
list1=[item for item in list1 if item [1]!= '']
list1=[item for item in list1 if item [2]!= '']
list1=[item for item in list1 if item [3]!= '']
list1=[item for item in list1 if item [4]!= '']
list1=[item for item in list1 if item [5]!= '']
list1=[item for item in list1 if item [6]!= '']

我尝试过类似以下的操作。我不确定如何在这种情况下正确地将列表传递给函数 - 但这里 x 是一个列表

def empty(x):
    x=list(x)
    # the range should be updated to the column length here
    # i've left it at 7 for illustration
    for i in range(7):
        x=x[for item in x if item [i]!='']
    return x

最佳答案

使用一些 python 内置函数怎么样 allfilter :

 x = [
    ['car','doug',''], 
    ['dede', 'eli', 'fred'], 
    ['law', '','frank'], 
    ['','roger','w'], 
    ['alex', 'berk' , 'carl']
]

# python 2.7
print filter(all, x)

# python 3.5
print(list(filter(all, x)))

- [['dede', 'eli', 'fred'], ['alex', 'berk', 'carl']]

过滤器评估谓词,并且仅在为真时才返回它

<小时/>

如果迭代器中的所有项都为 true,则 All 返回 true

关于python - 使用迭代和集合重写列表(根据条件删除条目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43460113/

相关文章:

python - 在 Django-imagekit Thumbnail 中停止自动旋转图像

python - 对列表中连续出现的相同重复项进行分组

java - 使用流从 map 列表中检索值

C# 列表属性

python-3.x - Python Tkinter GUI 与 PyQT 的内存节省

python - 在函数调用中混合 *vargs 和 **kargs 参数

python 3 : How do I sort both parallel lists?

python - 创建表示二进制值的字符串列表,具有固定长度

python - 将字典值分配给变量,其中 key == list[element]

python - 使用循环更新嵌套字典中的预先存在的值