在每个列表元素上调用 int() 函数? [英] Call int() function on every list element?
本文介绍了在每个列表元素上调用 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;
有必要这么丑吗?我确信在一行代码中有一种更 Pythonic 的方式来做到这一点.请帮帮我.
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() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文