@HIKARITAKA

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

for文など他の書き方ができるか知りたいです。Python3

解決したいこと

for文など他の書き方ができるか知りたいです。Python3

例)
いくつかの配列(x1~x3)があって、それらをリストとして足し算する場合、[x1]+[x2]+[x3]としているのですが、ループ等の書き方ができますでしょうか?

該当するソースコード

Python3

例)

import numpy as np

# x:3データ
x1 = np.random.rand(4,4)
x2 = np.random.rand(4,4)
x3 = np.random.rand(4,4)

x_123 = [x1] + [x2] + [x3]
# ↑この部分をループ文などで書き換えたいです。

print(x_123)
0 likes

2Answer

単純に配列を作りたいということであれば、以下のようにできると思います。

import numpy as np

x_123 = []

for i in range(3):
    x_123.append(np.random.rand(4,4))

print(x_123)

そうでなく、x1 , x2, x3 を処理したいということであれば eval を使ってみると可能だと思います(普通は使わないと思いますが)。

import numpy as np

x1 = np.random.rand(4,4)
x2 = np.random.rand(4,4)
x3 = np.random.rand(4,4)

x_123 = []
for i in range(3):
    x_123.append(eval("x{}".format(i+1)))

print(x_123)

(文字列の作り方は str.format() ではなくても、 f-string でも、string.Template でも、% 演算子 でも、好きな方法でやれば大丈夫です)

一応、for文の書き方で回答しましたが、内包表記なども使えると思います。

0Like

@yoshi389111
ありがとうございます。
前者の方法を使わせていただきたいと思います。
後者の方、現スクリプトを生かした方法も教えていただきありがとうございます。

0Like

Your answer might help someone💌