本文介绍了在每个列表元素上调用int()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含数字字符串的列表,如下所示:
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;
它必须很丑吗?我敢肯定,在一行代码中,还有一种更Python化的方法可以做到这一点.请帮帮我.
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.
推荐答案
这是列表理解用于:
numbers = [ int(x) for x in numbers ]
这篇关于在每个列表元素上调用int()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!