过滤功能在python 2.7中不起作用

时间:2017-02-09 15:02:00

标签: python

出于某种原因,我无法使用过滤功能。 我试图从列表中删除空字符串。阅读Remove empty strings from a list of strings后,我尝试使用过滤功能。

import csv
import itertools

importfile = raw_input("Enter Filename(without extension): ")
importfile += '.csv'
test=[]
#imports plant names, effector names, plant numbers and leaf numbers from csv file
with open(importfile) as csvfile:
    lijst = csv.reader(csvfile, delimiter=';', quotechar='|')
    for row in itertools.islice(lijst, 0, 4):
        test.append([row])

test1 = list(filter(None, test[3]))
print test1
然而,

然后返回:

[['leafs', '3', '', '', '', '', '', '', '', '', '', '']]

我做错了什么?

3 个答案:

答案 0 :(得分:0)

您可以过滤列表列表,其中内部项目是非空列表。

>>> print filter(None, [['leafs', '3', '', '', '', '', '', '', '', '', '', '']])
[['leafs', '3', '', '', '', '', '', '', '', '', '', '']]

如果过滤内部列表,包含字符串的列表,一切都按预期工作:

>>> print filter(None, ['leafs', '3', '', '', '', '', '', '', '', '', '', ''])
['leafs', '3']

答案 1 :(得分:0)

列表中有一个列表,因此filter(None, ...)应用于非空列表,空字符串不受影响。你可以使用嵌套列表理解来进入内部列表并过滤掉 falsy 对象:

lst = [['leafs', '3', '', '', '', '', '', '', '', '', '', '']]

test1 = [[x for x in i if x] for i in lst]
# [['leafs', '3']]

答案 2 :(得分:0)

我确实在过滤列表列表,我的代码中的问题是:

    for row in itertools.islice(lijst, 0, 4):
    test.append[row]

这应该是:

for row in itertools.islice(lijst, 0, 4):
        test.append(row)