简体   繁体   English

如何在 Python 中将数字列表转换为整数?

[英]How to Convert List of Numbers to Integers in Python?

So I have a list of lists of numbers from a .txt file loaded in Python:所以我有一个来自 Python 加载的 .txt 文件的数字列表列表:

ls = [['3456', '937'], ['3666', '54533'], ['24456', '83279'], ['344516', '10410']...]

How can I convert the numbers ( type: list ) to integers type, but keep them in this list?如何将数字( type: list )转换为整数类型,但将它们保留在此列表中?

Ie the output I'd like:即我想要的输出:

[[3456, 937], [3666, 54533], [24456, 83279], [344516, 10410]...]

I've tried using this:我试过用这个:

ls = [int(i) for i in ls]

But get the error: int() argument must be a string.但是得到错误: int() 参数必须是一个字符串。

Does anyone know how to do the conversion to the output I'd like?有谁知道如何转换为我想要的输出? Thanks!谢谢!

你可以在里面多用一个理解:

ls = [[int(i) for i in k] for k in ls]

You can use map and list comprehension.您可以使用map和列表理解。

ls = [['3456', '937'], ['3666', '54533'], ['24456', '83279'], ['344516', '10410']]

>>> [list(map(int, i)) for i in ls]
#[[3456, 937], [3666, 54533], [24456, 83279], [344516, 10410]]

List is mutable but string is not.列表是可变的,但字符串不是。 You can use for loop to achieve this.您可以使用 for 循环来实现此目的。

print(id(a[0]))
print(id(a[0][0]))

for i in range(len(a)):
    for j in range(len(a[i])):
        a[i][j] = int(a[i][j])

print(a)
print(type(a[0][0]))
print(id(a[0])) # the same id with the first print
print(id(a[0][1])) # id has changed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM