【问题标题】:csv python: generate list of tuples from rows in csvcsv python:从csv中的行生成元组列表
【发布时间】:2018-06-07 03:00:25
【问题描述】:

我有数千个内部格式相同的 csv 文件。行通常有八列,格式如下:

row1 = ['string in column 0', 'string in column 1', 'string in column 2'...]
row2 = ['string in column 0', 'string in column 1', 'string in column 2'...]
row3 = ['string in column 0', 'string in column 1', 'string in column 2'...]

对于每个文件,我想读取某些行并输出按行分隔的元组列表。例如,文件在前八列中有字符串,我希望最终输出为:

list_of_tuples = [('row1_col0','row1_col2','row1_col5','row1_col6'),('row2_col0','row2_col2','row2_col5','row2_col6'),...]

并不是所有的行都有四个值,所以我害怕生成四个列表,然后在它们被读入后构建一个元组。

到目前为止我构建的函数是

import csv

def list_of_tuples_from_csv(filepath_to_csv):
    total_text = []
    with open(file path_to_csv, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            total_text.append(tuple(row[0],row[2],row[5],row[6]))
    total_posts = list(set(total_text))
    return total_posts

但我得到一个错误阅读

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in list_of_tuples_from_csv
TypeError: tuple() takes at most 1 argument (4 given)

【问题讨论】:

  • 请发布数据样本
  • 发布完整的回溯,包括它发生的行。
  • 在力所能及的范围内回复了这两个问题。谢谢!

标签: python python-3.x csv tuples


【解决方案1】:

您不需要调用tuple 函数,只需将其放在括号中即可。

所以这一行

total_text.append(tuple(row[0],row[2],row[5],row[6]))

变成这样

total_text.append((row[0],row[2],row[5],row[6]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多