5
5

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次元配列の要素の和を求める

Last updated at Posted at 2018-01-26

2次元配列の要素の和を求めたくなった。
ただし、numpyが使えない環境で。

参考: numpyを使う場合

import numpy as np

# [0, 1]の100×100の配列 
twod_array = np.random.randint(0, 2, (100, 100))

result = twod_array.sum()

print(result)

2重ループ

あまりこんなことはしないと思うが……

import random

# [0, 1]の100×100の配列 
twod_array = [[random.randint(0, 1) for _ in range(100)] for _ in range(100)]

result = 0
for row in twod_array:
    for element in row:
        result += element

print(result)

sum関数

for文は残るけど。

import random

# [0, 1]の100×100の配列 
twod_array = [[random.randint(0, 1) for _ in range(100)] for _ in range(100)]

result = 0
for row in twod_array:
    result += sum(row)

print(result)

mapとsum関数

for文を使わずワンライナーでもかける。

import random

# [0, 1]の100×100の配列 
twod_array = [[random.randint(0, 1) for _ in range(100)] for _ in range(100)]

result = sum(map(sum, twod_array))

print(result)

結論

  • 実行速度は numpy < (sum+map) = (sum+for) < (for*2) みたいな感じだった。
  • numpyが使えるならnumpyを使おう。
5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?