Python将csv文件中的整数读入列表 [英] Python reading in integers from a csv file into a list

查看:390
本文介绍了Python将csv文件中的整数读入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试将csv文件中的特定列读入Python列表时遇到了一些麻烦.下面是我的csv文件的示例:

I am having some trouble trying to read a particular column in a csv file into a list in Python. Below is an example of my csv file:

Col 1       Col 2
1,000,000   1
  500,000   2
  250,000   3

基本上,我想将第1列作为整数添加到列表中,这样做很麻烦.我已经尝试过:

Basically I am wanting to add column 1 into a list as integer values and am having a lot of trouble doing so. I have tried:

for row in csv.reader(csvfile):
    list = [int(row.split(',')[0]) for row in csvfile]

但是,我收到一个ValueError,上面写着以10为底的int()无效文字:'"1'

However, I get a ValueError that says "invalid literal for int() with base 10: '"1'

然后我尝试:

for row in csv.reader(csvfile):
    list = [(row.split(',')[0]) for row in csvfile]

但是这次我没有收到错误,我得到了列表:

This time I don't get an error however, I get the list:

['"1', '"500', '"250']

我也尝试过更改定界符:

I have also tried changing the delimiter:

for row in csv.reader(csvfile):
    list = [(row.split(' ')[0]) for row in csvfile]

这几乎给了我所需的列表,但是该列表包括第二列以及每个值后的"\ n":

This almost gives me the desired list however, the list includes the second column as well as, "\n" after each value:

['"1,000,000", 1\n', etc...]

如果有人可以帮助我解决此问题,将不胜感激!

If anyone could help me fix this it would be greatly appreciated!

欢呼

推荐答案

您应该明智地选择定界符: 如果使用.的浮点数,请使用,分隔符,或者使用,的浮点数,请使用;作为分隔符.

You should choose your delimiter wisely : If you have floating numbers using ., use , delimiter, or if you use , for floating numbers, use ; as delimiter.

此外,由 csv.reader的文档引用您可以使用delimiter=参数来定义定界符,如下所示:

Moreover, as referred by the doc for csv.reader you can use the delimiter= argument to define your delimiter, like so:

with open('myfile.csv', 'r') as csvfile:
    mylist = []
    for row in csv.reader(csvfile, delimiter=';'):
        mylist.append(row[0]) # careful here with [0]

或简短版本:

with open('myfile.csv', 'r') as csvfile:
    mylist = [row[0] for row in csv.reader(csvfile, delimiter=';')]

要将数字解析为浮点数,您需要做

To parse your number to a float, you will have to do

 float(row[0].replace(',', ''))

这篇关于Python将csv文件中的整数读入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆