Python:二维列表中值赋值的混淆

时间:2017-10-28 03:30:44

标签: python-3.x

我在python中定义了一个二维数组,如下所示:

const makeTransaction = (fromID, toID, funds) => {
    let walletRegistry;
    let from;
    let to;

    businessNetworkConnection.connect(connectionProfile, businessNetworkIdentifier, participantId, participantPwd)
        .then((result) => {
            businessNetworkDefinition = result;
            return businessNetworkConnection.getAssetRegistry('org.acme.Wallet')
                .then(function (vr) {
                    walletRegistry = vr;
                    return walletRegistry.get(fromID);
                })
                .then(function (v) {
                    from = v;
                    return walletRegistry.get(toID);
                })
                .then(function (v) {
                    to = v;
                })
                .then(function () {
                    let serializer = businessNetworkDefinition.getSerializer();
                    let resource = serializer.fromJSON({
                        "$class": "org.acme.Transfer",
                        "amount": funds,
                        "from": {
                            "$class": "org.acme.Wallet",
                            "id": from.getIdentifier(),
                            "balance": from.balance,
                            "owner": "resource:org.acme.Client#" + from.owner.getIdentifier()
                        },
                        "to": {
                            "$class": "org.acme.Wallet",
                            "id": to.getIdentifier(),
                            "balance": to.balance,
                            "owner": "resource:org.acme.Client#" + to.owner.getIdentifier()
                        }
                    });
                    return businessNetworkConnection.submitTransaction(resource);
                });
        }).then((result) => {
            console.log(chalk.blue(' ------ All done! ------'));
            console.log('\n');
            return businessNetworkConnection.disconnect();
        }).catch(function (error) {
            businessNetworkConnection.disconnect();
            throw error;
        });
}

我希望将一个元素分配为2,例如:

a = [[1]*3]*3

然而,结果是:

a[1][1] = 2

而不是我的想法:

[[1,2,1],[1,2,1],[1,2,1]]

任何人都有任何想法?

The ScreenShot of the code

2 个答案:

答案 0 :(得分:0)

您可以使用列表理解来完成:

a=[[1 for _ in range(3)] for _ in range(3)]

a
Out[32]: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

a[1][1]=2

a
Out[34]: [[1, 1, 1], [1, 2, 1], [1, 1, 1]]

答案 1 :(得分:0)

我认为在括号内使用括号是将None值项设为0并且它首先将内部乘法相乘/解包,因此您的引用[1] [1]指的是元列表[[1]因为操作的顺序,在第二次乘法发生之前,将第二个元素的第二个元素转换为2,然后得出第二个元素。