filter函数的目的是从列表(或一般情况下,任何iterable)中选择满足特定条件的元素。它并不是真正用于基于索引的选择。因此,尽管您可以使用它来挑选CSV文件的指定列,但我不推荐它。相反,您可能应该使用这样的方法:with open(filename, 'rb') as f:
for record in csv.reader(f):
do_something_with(record[0], record[2])
根据您对记录的具体操作,最好在感兴趣的列上创建迭代器:
^{pr2}$
或者,如果您需要非顺序处理,可以使用一个列表:with open(filename, 'rb') as f:
the_list = [(record[0], record[2]) for record in csv.reader(f)]
# do something with the list
我不知道你在列中定义数据是什么意思。数据由CSV文件定义。在
相比之下,这里有一个您希望使用filter的情况:假设您的CSV文件包含数字数据,您需要构建一个记录列表,其中的数字在行中严格按递增顺序排列。您可以编写一个函数来确定数字列表是否严格按递增顺序排列:def strictly_increasing(fields):
return all(int(i) < int(j) for i,j in pairwise(fields))
(有关pairwise的定义,请参见^{} documentation)。然后您可以将其用作filter中的条件:with open(filename, 'rb') as f:
the_list = filter(strictly_increasing, csv.reader(f))
# do something with the list
当然,同样的事情也可以,而且通常也会作为列表理解来实现:with open(filename, 'rb') as f:
the_list = [record for record in csv.reader(f) if strictly_increasing(record)]
# do something with the list
所以在实践中没有理由使用filter。在