Python将列表中的字符串转换为数字 [英] Python converting strings in a list to numbers

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

问题描述

我遇到了以下错误消息:

I have encountered the below error message:

以10为底的int()无效文字:"2"'

invalid literal for int() with base 10: '"2"'

2外面用单引号括起来,而内部用双引号括起来.此数据位于使用print primes[0]primes列表中.

The 2 is enclosed by single quotes on outside, and double quotes on inside. This data is in the primes list from using print primes[0].

primes列表中的样本数据:

["2","3","5","7"]

primes列表是通过以下方式从CSV文件创建的:

The primes list is created from a CSV file via:

primes=csvfile.read().replace('\n',' ').split(',')

我正在尝试将primes列表中的字符串转换为整数.

I am trying to trying to convert strings in primes list into integers.

通过Google,我在SE上遇到了类似的问题,并且尝试了与我的问题IMO相关的两个常见答案.

Via Google I have come across similar questions to mine on SE, and I have tried the two common answers that are relevant to my problem IMO.

使用map():

primes=map(int,primes)

使用列表理解:

primes=[int(i) for i in primes]

不幸的是,当我使用它们中的任何一个时,它们都给出与上面列出的相同的错误消息.使用long()而不是int()时,我也会收到类似的错误消息.

Unfortunately when I use either of them these both give the same error message as listed above. I get a similar error message for long() when used instead of int().

请告知.

推荐答案

您想要的:

  • 读取每条csv行
  • 使用所有行的展平版本创建单个整数列表.

因此,您必须处理引号(有时取决于文件的创建方式,有时甚至可能不在引号中),而且当您用空格替换换行符时,也不能用下一行的第一个数字.你有很多问题.

So you have to deal with the quotes (sometimes they may even not be here depending on how the file is created) and also when you're replacing linefeed by space, that doesn't split the last number from one line with the first number of the next line. You have a lot of issues.

改为使用csv模块.说f是打开文件的句柄,然后:

Use csv module instead. Say f is the handle on the opened file then:

import csv

nums = [int(x) for row in csv.reader(f) for x in row]

解析单元格的

,如果有引号,则将其删除,然后将其展平+转换为整数,并在一行中显示.

that parses the cells, strips off the quotes if present and flatten + convert to integer, in one line.

要限制读取的数字数量,可以创建一个生成器理解而不是一个列表理解,并且仅消耗前n个项:

To limit the number of numbers read, you could create a generator comprehension instead of a list comprehension and consume only the n first items:

n = 20000 # number of elements to extract
z = (int(x) for row in csv.reader(f) for x in row)
nums = [next(z) for _ in xrange(n)] # xrange => range for python 3

更好的是,为避免出现StopIteration异常,您可以改用itertools.islice,因此,如果csv数据结束,您将获得完整列表:

Even better, to avoid StopIteration exception you could use itertools.islice instead, so if csv data ends, you get the full list:

nums = list(itertools.islice(z,n))

(请注意,您必须倒退文件以多次调用此代码,否则将没有任何元素)

(Note that you have to rewind the file to call this code more than once or you'll get no elements)

在没有的情况下执行此任务当然可以([int(x.strip('"')) for x in csvfile.read().replace('\n',',').split(',')]),但是更复杂且容易出错.

Performing this task without the csv module is of course possible ([int(x.strip('"')) for x in csvfile.read().replace('\n',',').split(',')]) but more complex and error-prone.

这篇关于Python将列表中的字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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