如何在重复编号的python中创建矩阵?

时间:2018-12-11 05:03:21

标签: python loops matrix iterator

我要:
创建一个从0到4的矢量列表,即[0,1,2,3,4],然后从该列表开始
创建一个矩阵,该矩阵包含一个0到4的“分层列表”,重复3次,每个维度一次。矩阵有4 ^ 3 = 64行,因此

T = [0 0 0    
       0 0 1  
       0 0 2  
       0 0 3  
       0 0 4  
       0 1 0  
       0 1 1  
       0 1 2  
       0 1 3  
       0 1 4  
       0 2 0  
       ...  
       1 0 0  
       ...  
       1 1 0  
       ....  
       4 4 4]    

这是我到目前为止所拥有的:

n=5;
ind=list(range(0,n))
print(ind)

我刚开始使用Python,因此将不胜感激!

3 个答案:

答案 0 :(得分:4)

python itertools module product()函数可以做到这一点:

for code in itertools.product( range(5), repeat=3 ):
    print(code)

给出结果:

(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
...
(4, 4, 2)
(4, 4, 3)
(4, 4, 4)

因此,将其转换为矩阵:

import itertools
matrix = []
for code in itertools.product( range(5), repeat=3 ):
     matrix.append( list(code) )

答案 1 :(得分:0)

 list_ = []
 for a in range(5):
     for b in range(5):
        for c in range(5):
              list_ += [a ,b ,c ]

 print(list_)

答案 2 :(得分:0)

请注意,您确实希望矩阵具有5 ^ 3 = 125行。基本答案是只在嵌套的for循环中进行迭代:

for ($i=0; $i < count($_POST['q1']); $i++){
    $question = $_POST['q1'][$i];
    $choice1 = $_POST['c1'][$i];
    $choice2 = $_POST['c2'][$i];
    $choice3 = $_POST['c3'][$i];
    $choice4 = $_POST['c4'][$i];
    $correct = $_POST['ca'][$i];    

    $store_question = "INSERT INTO quiz (question, choice1, choice2, choice3, choice4, correct) VALUES ('$question', '$choice1', '$choice2', '$choice3', '$choice4', '$correct')";
    $result_get_question = mysqli_query($conn, $store_question);
}  

还有其他可能更快的方法,但是要想达到更快的速度,就很难做到这一点。