【问题标题】:filter lists of lists by taking out items less than a certain length - more pythonic way?通过取出小于一定长度的项目来过滤列表列表 - 更pythonic的方式?
【发布时间】:2014-07-01 17:32:35
【问题描述】:

我正在阅读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']]

【问题讨论】:

    标签: python list


    【解决方案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]
    

    在其中任何一个中。

    【讨论】:

    • 哇,我不知道你可以做这样的事情!
    • 或者只是listy = [ [x for x in ilist if len(x)] for ilist in indexdf],因为len(x) 除了零之外的所有值都将被视为真。
    【解决方案2】:

    您可以在此处使用嵌套列表推导。请注意,空字符串将在布尔上下文中返回 False。空列表、元组等也是如此。

    >>> lst = [['1','','1',], ['1', '']] 
    >>> lst = [[x for x in sl if x] for sl in lst]
    >>> lst
    [['1', '1'], ['1']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 2020-05-05
      相关资源
      最近更新 更多