简体   繁体   中英

How can I convert the string values of a 2D array to integer values in Python?

I've got a code like this:

a=[['1','2','3'], ['4','5','6']]

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

print(a)

Output:

[[1, '2', '3'], ['4', 5, '6']]

It only converted the first value into an integer and left the rest as a string. Is there a solution to this?

You can map your sublists to int type within a list comprehension.

a = [['1','2','3'], ['4','5','6']]

a_new = [list(map(int, i)) for i in a]

# [[1, 2, 3], [4, 5, 6]]

You can use a nested list comprehension:

a = [['1','2','3'], ['4','5','6']]

a = [[int(v) for v in l] for l in a]
print(a)

Output:

[[1, 2, 3], [4, 5, 6]]

You only get the first element of each row converted to int because your for-loop is not correct. You need a double-for-loop to get to all the elements of each row and column :

This should work:

a=[['1','2','3'], ['4','5','6']]

row_number= len(a)
column_number = len(a[0])

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

Use a numpy array :

import numpy as np

a = [['1','2','3'], ['4','5','6']]
output = np.array(a, dtype=np.int)

The numpy implementation will be more efficient than the one you attempted.

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