4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[小ネタ][Python] 2次元配列の文字列を数値に置換する

Posted at

Pythonの2次元配列に格納した文字列を数値に置換する方法についてメモ。
たとえば標準入力で以下のように数字が渡される。

3
1 2
3 4
5 6

1行目は2行目移行の標準入力の繰り返し回数。
で、2行目移行の数値は2次元配列に格納したい。

arr = []
n = int(input())
for i in range(n):
    arr.append(input().split())
print(arr)
>>>[['1', '2'], ['3', '4'], ['5', '6']]

このときinput().split()で入力を受け取ると、文字列のリストとして入力される。
これをintに変換したい。

forで変換する場合

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]]

おまけ:1次元配列にしちゃう場合

arr = [int(x) for y in arr for x in y]
print(arr)
>>>[1, 2, 3, 4, 5, 6]
4
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?