[英]Converting list to string then integer
I have a list with 1550500 numbers, and all of them with quotes. 我有一个包含1550500数字的列表,并且所有数字都带有引号。 Example: list('100', '150', '200', '250') etc... I need to sum all the numbers, but before that I need to convert it to INT.
示例:list('100','150','200','250')等...我需要对所有数字求和,但是在此之前,我需要将其转换为INT。
List Name: trip_list 清单名称:trip_list
My code: 我的代码:
mean_tripstr = str(trip_list)
mean_trip = [int(x) for x in mean_tripstr]
print(type(mean_trip))
Error message: 错误信息:
Traceback (most recent call last):
File "projeto1.py", line 235, in <module>
mean_trip = [int(x) for x in mean_tripstr]
File "projeto1.py", line 235, in <listcomp>
mean_trip = [int(x) for x in mean_tripstr]
ValueError: invalid literal for int() with base 10: '['
What am I doing wrong? 我究竟做错了什么? I am new to coding...
我是编码新手...
You have to convert each element to int
: 您必须将每个元素转换为
int
:
mean_tripstr = map(str,trip_list)
mean_trip = list(map(int,mean_tripstr))
The code above uses a generator
, what is more efficient in cases when you just have to iterate in a list. 上面的代码使用了
generator
,在只需要迭代列表的情况下,效率更高。 The last line convert to a list again properly. 最后一行再次正确转换为列表。
But, as you said, if you already have a list of strings, you can just do: 但是,正如您所说,如果您已经有一个字符串列表,则可以执行以下操作:
mean_trip = list(map(int,trip_list))
If you know numpy
, you can do too: 如果您知道
numpy
,也可以这样做:
import numpy as np
trip_list = np.array(trip_list)
mean_trip = trip_list.astype(np.int)
Python has a map function, this takes a function and an iterable. Python有一个map函数,它需要一个函数并且是可迭代的。 There is also the sum function, which returns the sum of an iterable.
还有求和函数,它返回一个可迭代的和。
You can use this: 您可以使用此:
sum(map(int(trip_list))
Note that the map function does not return a list, it returns a generator. 注意,map函数不返回列表,而是返回一个生成器。 To convert it to a list, use
要将其转换为列表,请使用
list(sum(map(int, trip_list)))
(this may take a while as it requires iterating over the entire list, and yours is quite long). (这可能需要一段时间,因为它需要遍历整个列表,而且您的列表很长)。
The error with your code is converting your list to a string, that is, 代码错误将列表转换为字符串,即
>>> my_list = ["5", "6"]
>>> my_list_str = str(my_list)
>>> my_list_str
"['5', '6']"
>>> type(my_list_str)
<class 'str'>
>>> type(my_list)
<class 'list'>
So when you try to iterate over the string, the first x
is [
which is not a number (thus the exception). 因此,当您尝试遍历字符串时,第一个
x
是[
这不是数字(因此是例外)。
As a sidenote, using list(map(int, a_list))
is faster than [int(i) for i in a_list]
附带说明一下,使用
list(map(int, a_list))
a, list(map(int, a_list))
比[int(i) for i in a_list]
要快
>>> c1 = "list(map(int, a_list))"
>>> c2 = "[int(i) for i in a_list]"
>>> s = "a_list = [str(i) for i in range(1000)]"
>>> import timeit
>>> timeit.timeit(c1, setup=s, number=10000)
1.9165708439999918
>>> >>> timeit.timeit(c2, setup=s, number=10000)
2.470973639999997
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.