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