filter 函数旨在从列表(或一般来说,任何可迭代的)中选择满足特定条件的那些元素。它并不是真正用于基于索引的选择。因此,尽管您可以使用它来挑选 CSV 文件的指定列,但我不推荐它。相反,您可能应该使用这样的东西:
with open(filename, 'rb') as f:
for record in csv.reader(f):
do_something_with(record[0], record[2])
根据您对记录的具体操作,最好在感兴趣的列上创建一个迭代器:
with open(filename, 'rb') as f:
the_iterator = ((record[0], record[2]) for record in csv.reader(f))
# do something with the iterator
或者,如果您需要非顺序处理,也许是一个列表:
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))
(参见itertools documentation 了解pairwise 的定义)。然后你可以把它作为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。