【问题标题】:Using the filter function in Python在 Python 中使用过滤器函数
【发布时间】:2011-11-28 04:36:16
【问题描述】:

我正在尝试使用 Python 的内置过滤器功能从 CSV 中的某些列中提取数据。这是对过滤功能的好用吗?我必须先定义这些列中的数据,还是 Python 已经知道哪些列包含哪些数据?

【问题讨论】:

  • 您能否提供输入数据和请求的输出数据的示例?
  • 你能更详细地解释你想要做什么吗?也许举个例子?我不清楚...
  • 当然。假设我的 CSV 有第 1、2 和 3 列。我想忽略第 2 列中的所有数据,只提取第 1 列和第 3 列中的数据。这可以使用过滤器功能实现吗?
  • 这没什么好解释的,但我想还是要继续下去……
  • 您应该使用 stdlib 的 csv 模块读取 CSV 文件,如下面“number5”的回答。内置的filter 最好留作他用

标签: python csv filter


【解决方案1】:

由于 python 吹嘘“包含电池”,对于大多数日常情况,可能已经有人提供了解决方案。 CSV就是其中之一,还有built-in csv module

另外,tablib 是一个非常好的第 3 方模块,尤其是您处理非 ascii 数据时。

对于您在评论中描述的行为,这样做:

import csv
with open('some.csv', 'rb') as f:
   reader = csv.reader(f)
   for row in reader:
      row.pop(1)
      print ", ".join(row)

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多