【问题标题】:Read csv of ints into single list in Python将整数的csv读入Python中的单个列表
【发布时间】:2019-05-09 22:38:55
【问题描述】:

我有一个整数 csv,我想将它们全部读入 Python 中的一个列表中。我该怎么做?

我在这里搜索了一堆,我尝试的每段代码都会输出一行整数作为列表,从而创建一个列表列表。

理想情况下,我正在寻找这样的输出:[2,4,6,6,4,6,4,12,12,4],但我不断得到这个:[[2,4,6,6,4,'',],[6,4,12,12,4,'',],...]

这是 csv 的 sn-p:

【问题讨论】:

  • 请出示您的代码
  • 和 csv 文件
  • 发布一些您已经尝试过的代码,我们将帮助您使其更好地工作。 csv 文件的 sn-p 也会有帮助!
  • 我添加了一个 csv 的 sn-p。我做了一个错误的选择,没有保留我测试过以前实现的文件。我将确保在以后的帖子中包含过去的代码。我道歉!

标签: python-3.x csv


【解决方案1】:

我认为这对你有用:

import csv

path = 'text.csv'                #change to path of your csv file
thelist = []                     #define new list

with open(path, 'r') as csvfile: #open csv file
    reader = csv.reader(csvfile) #read it
    for row in reader:           #iterate through each row 
        for item in row:         #iterate through each item of that row
            thelist.append(int(item)) #convert item to an int and add it to thelist


print(thelist)                   #print it

请注意,csv 文件中的所有项目都必须是整数才能正常工作,否则会引发错误。您可以将int(item) 更改为item 以获取字符串列表

文本.csv:

1,2,3,4,5,6
7,8,9,0,1,2
3,4,5,6,7,8
4,5,6,7,8,9

输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9]

奖金,可能没用,单行(没有csv 模块):

使用列表理解:

thelist = [int(item) for item in open('text.csv').read().replace('\n', ',').split(',')]

...或者,map:

thelist = list(map(int, open('text.csv').read().replace('\n', ',').split(',')))

...或者with,使用后会自动关闭文件:

with open('text.csv') as f: thelist = list(map(int, f.read().replace('\n',',').split(',')))

Run and edit these one-liners online

【讨论】:

  • 如果你使用oneliner,你最终会得到资源警告跟踪malloc,你如何关闭文件?
  • @NandeepDevendra - 我已经编辑了我的答案以包含一个使用with open(... 而不仅仅是open 打开文件的单行,它应该在完成阅读后关闭文件。让我知道这是否适合您。
  • 很好,现在可以使用了,谢谢
【解决方案2】:

使用list.extend() 将单元格项目添加到列表中:

import csv 

with open('data.csv', 'r') as csvfile:
    mylist = []
    for row in csv.reader(csvfile, delimiter=','):
        mylist.extend(map(int,row))

>>> print(mylist)
[2, 4, 6, 6, 4, 6, 4, 12, 12, 4]

【讨论】:

  • 这个解决方案也有效!只是想给予适当的信任。
猜你喜欢
  • 2018-05-07
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 2021-04-16
相关资源
最近更新 更多