python中filter是什么意思_在Python中使⽤filter函数
filter函数的⽬的是从列表(或⼀般情况下,任何iterable)中选择满⾜特定条件的元素。它并不是真正⽤于基于索引的选择。因此,尽管您可以使⽤它来挑选CSV⽂件的指定列,但我不推荐它。相反,您可能应该使⽤这样的⽅法:with open(filename, 'rb') as f:
for record ader(f):
do_something_with(record[0], record[2])
根据您对记录的具体操作,最好在感兴趣的列上创建迭代器:
^{pr2}$
或者,如果您需要⾮顺序处理,可以使⽤⼀个列表:with open(filename, 'rb') as f:
the_list = [(record[0], record[2]) for record ader(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, ader(f))
# do something with the list
当然,同样的事情也可以,⽽且通常也会作为列表理解来实现:with open(filename, 'rb') as f:
the_list = [record for record ader(f) if strictly_increasing(record)]
# do something with the list
所以在实践中没有理由使⽤filter。在
record是什么意思中文