关于数组上嵌套循环的问题

时间:2017-09-09 13:07:54

标签: python python-3.x list

s = [[0]*3]*3

i = 0 
while i < 3:
    j = 0
    while j < 3:
        print(s[i][j])
        s[i][j] += 1
        j += 1
    i += 1

上述代码的打印结果让我很困惑,为什么数组的第二列和第三列变为[1,1,1][2,2,2]而不是[0,0,0]

2 个答案:

答案 0 :(得分:1)

因为当您使用[[0]*3]*3创建列表列表时,您创建了一个列表[0,0,0]三次,因此您将拥有[[0,0,0],[0,0,0],[0,0,0]],但所有子列表( [0,0,0])确实正在刷新相同的列表,因为您刚刚创建了一个并将其乘以3来创建其他列表,因此更改一个列表将对其他列表进行更改。
要防止这种情况,请使用列表解析创建独立的零列表:

s = [[0]*3 for i in range(3)]

i = 0 
while i < 3:
    j = 0
    while j < 3:
        print(s[i][j])
        s[i][j] += 1
        j += 1
    i += 1
print(s) # just to see the final result

哪个输出:

0
0
0
0
0
0
0
0
0
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]

答案 1 :(得分:0)

因为您创建数组的方式是

import numpy as np
s = np.zeros((3,3))      #in this way you can get a 3*3 array
i = 0
while i < 3:
    j = 0
    while j < 3
        s[i][j] += i     #not plus 1,otherwise you will get [[1,1,1],[1,1,1],[1,1,1]]
        j += 1
    i += 1

表示s的所有元素都是相同的列表,一旦你更改了其中一个元素,其余元素也会被更改 所以如果你想得到[[0,0,0],[1,1,1],[2,2,2]],你可以试试这个:

$username = $_POST["username"];

                                  // SELECT what you want
$statement = mysqli_prepare($con,"SELECT * FROM user WHERE username = ?");

mysqli_stmt_bind_param($statement,"s",$username);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);

mysqli_stmt_bind_result($statement, 
                        $userID, 
                        $username, 
                        $password, 
                        $email, 
                        $age, 
                        $realname, 
                        $streetname, 
                        $postcode, 
                        $city,
                        $state);

$response = array();

$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;        
    $response["username"] = $username;
    $response["password"] = $password;
    $response["email"] = $email;
    $response["age"] = $age;
    $response["realname"] = $realname;
    $response["streetname"] = $streetname;
    $response["postcode"] = $postcode;
    $response["city"] = $city;
    $response["state"] = $state;        
}

echo json_encode($response);