python - 通过取出小于一定长度的项目来过滤列表的列表 - 更Pythonic的方式?

标签 python list

我正在阅读this ,但我不确定如何执行相同的操作来查看列表中各个项目的长度。我下面有以下庞大的代码,我想知道是否有更Pythonic的方法来做到这一点?

indexdf =   [['1','','1',], ['1', '']]

listy = []
for ilist in indexdf:
    listx = [ ]
    #print ilist
    for x in ilist:
        #print x
        if len(x) > 0:
            listx.append(x)
    listy.append(listx)

输出

listy = [['1','1']. ['1']]

最佳答案

listy = [ [x for x in ilist if len(x) > 0] for ilist in indexdf]

还有一个进一步的技巧,因为示例中的“一定长度”恰好排除了空字符串:

[x for x in ilist if len(x) > 0]

可以替换为

list(filter(None, ilist))

在 Python 3 中或只是

filter(None, ilist)

在 Python 2 中,或

[x for x in ilist if x]

在其中任何一个中。

关于python - 通过取出小于一定长度的项目来过滤列表的列表 - 更Pythonic的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24516164/

相关文章:

Python:如何使用 xml.dom.minidom 获取 XML 元素的文本内容?

css - 克服在我的 List Flex4 上设置的主题属性

c# - 如何在 C# 中将二维数组转换为二维列表

python - 在 Python 中使用自定义顺序对列表进行排序

Python 连接与列表追加速度

python - 不使用类/对象递归创建树层次结构

python - Pandas 数据框中的日期时间不会相互减去

python - 将产量分成小于 Python 阈值的部分

python - 空字符串而不是不匹配的组错误

c# - 从CheckedListBox获取CheckBox的标签文本