python中filter是什么意思_在Python中使用filter函数

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。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值