当前位置: 代码迷 >> python >> 过滤器功能在python 2.7中不起作用
  详细解决方案

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

热度:100   发布时间:2023-06-13 14:50:41.0

由于某种原因,我无法使过滤器功能正常工作。 我正在尝试从列表中删除空字符串。 阅读了之后,我试图利用过滤器功能。

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', '', '', '', '', '', '', '', '', '', '']]

我究竟做错了什么?

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

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

如果您过滤内部列表(包含字符串的列表),那么一切都会按预期进行:

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

您在列表中有一个列表,因此将filter(None, ...)应用于非空列表,不影响空字符串。 您可以使用说一个嵌套列表理解来到达内部列表并过滤出虚假对象:

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

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

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

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

应该是:

for row in itertools.islice(lijst, 0, 4):
        test.append(row)
  相关解决方案