简体   繁体   中英

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:

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?

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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