如何将字符串列表更改为整数 - Python

发布于 2024-11-30 03:02:01 字数 91 浏览 1 评论 0原文

我需要将字符串列表更改为整数列表,我该怎么做,

即将

('1', '1', '1', '1', '2') 更改为 (1,1,1,1, 2)。

I need to change a list of strings into a list of integers how do i do this

i.e

('1', '1', '1', '1', '2') into (1,1,1,1,2).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

温暖的光 2024-12-07 03:02:01

使用列表推导式

strtuple = ('1', '1', '1', '1', '2')
intlist = [int(s) for s in strtuple]

完整性的东西:

因为你的“列表”在事实是 tuple,即不可变列表,您必须使用生成器表达式与元组构造函数一起返回另一个元组:

inttuple = tuple(int(s) for s in strtuple)

我所说的“生成器表达式”在未包装在构造函数调用中时看起来像这样,并以这种方式返回生成器。

intgenerator = (int(s) for s in strtuple)

Use list comprehensions:

strtuple = ('1', '1', '1', '1', '2')
intlist = [int(s) for s in strtuple]

Stuff for completeness:

As your “list” is in truth a tuple, i.e. a immutable list, you would have to use a generator expression together with a tuple constructor to get another tuple back:

inttuple = tuple(int(s) for s in strtuple)

The “generator expression” i talk about looks like this when not wrapped in a constructor call, and returns a generator this way.

intgenerator = (int(s) for s in strtuple)
星光不落少年眉 2024-12-07 03:02:01
map(int, ls)

其中 ls 是您的字符串列表。

map(int, ls)

Where ls is your list of strings.

明月松间行 2024-12-07 03:02:01

使用map函数。

vals = ('1', '1', '1', '1', '2')
result = tuple(map(int, vals))
print result

输出:

(1, 1, 1, 1, 2)

与列表理解的性能比较:

from timeit import timeit
print timeit("map(int, vals)", "vals = '1', '2', '3', '4'")
print timeit("[int(s) for s in strlist]", "strlist = ('1', '1', '1', '1', '2')")

输出:

3.08675879197
4.08549801721

对于较长的列表:

print timeit("map(int, vals)", "vals = tuple(map(str, range(10000)))", number = 1000)
print timeit("[int(s) for s in strlist]", "strlist = tuple(map(str, range(10000)))", number = 1000)

输出:

6.2849350965
7.36635214811

在这种情况下(在我的机器上),map 方法似乎比列表理解更快。

Use the map function.

vals = ('1', '1', '1', '1', '2')
result = tuple(map(int, vals))
print result

Output:

(1, 1, 1, 1, 2)

A performance comparison with the list comprehension:

from timeit import timeit
print timeit("map(int, vals)", "vals = '1', '2', '3', '4'")
print timeit("[int(s) for s in strlist]", "strlist = ('1', '1', '1', '1', '2')")

Output:

3.08675879197
4.08549801721

And with longer lists:

print timeit("map(int, vals)", "vals = tuple(map(str, range(10000)))", number = 1000)
print timeit("[int(s) for s in strlist]", "strlist = tuple(map(str, range(10000)))", number = 1000)

Output:

6.2849350965
7.36635214811

It appears that, (on my machine) in this case, the map approach is faster than the list comprehension.

就此别过 2024-12-07 03:02:01

您可以使用列表理解,其大致如下所示:

newList = [int(x) for x in oldList]

You could use list comprehension which would look roughly like:

newList = [int(x) for x in oldList]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文