【问题标题】:How do I create a list from a CSV file column?如何从 CSV 文件列创建列表?
【发布时间】:2020-09-21 21:45:14
【问题描述】:

我对编码相当陌生,我需要将 CSV 文件中的列放入列表中。我不能使用任何像 Pandas 这样的库。这是我拥有的当前代码,但它单独获取每个字符。我需要更改哪些内容才能使用整个单词?

def readfile(f):
    with open(f) as csv_file:
        csv_reader= csv.reader(csv_file, delimiter= ',')
        
        for i in csv_reader:
            newlist= list(i[1])
            print(newlist)

这是创建的输出示例。

['P', 'O', 'P', 'U', 'L', 'A', 'T', 'I', 'O', 'N']
['5', '2', '2', ',', '8', '1', '8']
['1', '5', '5', ',', '6', '5', '6']
['9', '6', '6', ',', '7', '0', '9']
['7', '7', '3', ',', '8', '8', '7']
['8', ',', '4', '4', '7', ',', '6', '0', '9']
['1', '4', ',', '4', '8', '4', ',', '2', '4', '2']
['1', ',', '3', '6', '4', ',', '4', '0', '0']
['1', ',', '1', '7', '1', ',', '0', '2', '7']
['4', ',', '3', '5', '0', ',', '9', '0', '1']
['5', ',', '0', '4', '6', ',', '7', '8', '0']
['4', '0', ',', '6', '0', '1']
['4', '4', ',', '9', '0', '9']
['3', '8', ',', '6', '6', '6']

我需要它们都在一个列表中,例如[522,818 , 155,656 , etc]

【问题讨论】:

  • 不要做list(i[1])。您将字符串转换为字母列表。
  • 您是说要将所有行的输出连接到一个列表中吗?例如,您有两行(第 1 行:[1,2])和(第 2 行:[3,4])。您想生成一个包含 [1,2,3,4] 的列表吗?
  • 发布 CSV 文件的前 10 行。

标签: python list csv


【解决方案1】:

假设您想连接每行包含一个列表的 csv 中的行,这样输入的 csv 看起来像:

population
1,2
3,4

将打印 -> [1,2,3,4]

您可以在 python list 内置函数上使用 extend 函数。 下面是它的外观:

import csv
with open('example.csv') as ff:
     reader = csv.reader(ff)
     reader.next() # skip the header that you arent using
     concat_output = []
     for row in reader:
         concat_output.extend(row)
     print(concat_output)

【讨论】:

    【解决方案2】:

    也许这就是你要找的:

    >>>''.join(['5', '2', '2', ',', '8', '1', '8'])
    '522,818'
    

    我刚刚发现这个较早的帖子提供了更多背景/术语:How to concatenate items in a list to a single string?

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 2023-03-22
      • 2015-09-16
      • 2018-04-14
      • 1970-01-01
      • 2016-07-18
      • 2013-11-19
      • 2011-05-06
      相关资源
      最近更新 更多