问题:在每个列表元素上调用int()函数?

我有一个包含数字字符串的列表,如下所示:

numbers = ['1', '5', '10', '8'];

我想将每个列表元素都转换为整数,所以它看起来像这样:

numbers = [1, 5, 10, 8];

我可以使用循环来做到这一点,就像这样:

new_numbers = [];
for n in numbers:
    new_numbers.append(int(n));
numbers = new_numbers;

一定很丑吗?我敢肯定,在一行代码中,还有一种更Python化的方法可以做到这一点。请帮帮我。

I have a list with numeric strings, like so:

numbers = ['1', '5', '10', '8'];

I would like to convert every list element to integer, so it would look like this:

numbers = [1, 5, 10, 8];

I could do it using a loop, like so:

new_numbers = [];
for n in numbers:
    new_numbers.append(int(n));
numbers = new_numbers;

Does it have to be so ugly? I’m sure there is a more pythonic way to do this in a one line of code. Please help me out.


回答 0

这是列表推导的目的:

numbers = [ int(x) for x in numbers ]

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ]

回答 1

在Python 2.x中,另一种方法是使用map

numbers = map(int, numbers)

注意:在Python 3.x中,map返回一个地图对象,如果需要,可以将其转换为列表:

numbers = list(map(int, numbers))

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

回答 2

只是一点

numbers = [int(x) for x in numbers]

列表理解更自然,而

numbers = map(int, numbers)

是比较快的。

在大多数情况下,这可能无关紧要

有用的读物​​:LP vs地图

just a point,

numbers = [int(x) for x in numbers]

the list comprehension is more natural, while

numbers = map(int, numbers)

is faster.

Probably this will not matter in most cases

Useful read: LP vs map


回答 3

如果打算将这些整数传递给函数或方法,请考虑以下示例:

sum(int(x) for x in numbers)

这种构造有意显着地类似于adamk提到的列表理解。没有方括号,它称为生成器表达式,是一种将内存列表传递给方法的非常节省内存的方法。这里有一个很好的讨论:生成器表达式与列表理解

If you are intending on passing those integers to a function or method, consider this example:

sum(int(x) for x in numbers)

This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it’s called a generator expression, and is a very memory-efficient way of passing a list of arguments to a method. A good discussion is available here: Generator Expressions vs. List Comprehension


回答 4

在Python 3中制作的另一种方法:

numbers = [*map(int, numbers)]

Another way to make it in Python 3:

numbers = [*map(int, numbers)]


回答 5

其他方式,

for i, v in enumerate(numbers): numbers[i] = int(v)

Another way,

for i, v in enumerate(numbers): numbers[i] = int(v)

回答 6

以为我会合并答案并显示一些timeit结果。

Python 2在这方面很糟糕,但是map比理解要快一点。

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3本身的速度要快4倍以上,但是将map生成器对象转换为列表仍然比理解要快,并且通过解压缩map生成器来创建列表(感谢Artem!)仍然要快一些。

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

注意:在Python 3中,似乎4个元素是交叉点(在Python 2中为3个),尽管对于生成一个以上元素的列表而言,解压缩生成器仍然比任何一个都快,但理解速度稍快一些。

Thought I’d consolidate the answers and show some timeit results.

Python 2 sucks pretty bad at this, but map is a bit faster than comprehension.

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3 is over 4x faster by itself, but converting the map generator object to a list is still faster than comprehension, and creating the list by unpacking the map generator (thanks Artem!) is slightly faster still.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。