A note on how to replace a string stored in a Python two-dimensional array with a number. For example, in standard input, numbers are passed as follows.
3
1 2
3 4
5 6
The first line is the number of repetitions of standard input for the transition to the second line. So, I want to store the numerical value of the transition to the second line in a two-dimensional array.
arr = []
n = int(input())
for i in range(n):
arr.append(input().split())
print(arr)
>>>[['1', '2'], ['3', '4'], ['5', '6']]
At this time, if input is received by input (). Split (), it will be input as a list of character strings. I want to convert this to an int.
for i in range(len(arr)):
for j in range(len(arr[i])):
arr[i][j] = int(arr[i][j])
print(arr)
>>>[[1, 2], [3, 4], [5, 6]]
arr = [[int(x) for x in y] for y in arr]
print(arr)
>>>[[1, 2], [3, 4], [5, 6]]
arr = [int(x) for y in arr for x in y]
print(arr)
>>>[1, 2, 3, 4, 5, 6]
Recommended Posts