简体   繁体   English

遍历和更改Python中的嵌套列表条目

[英]Iterating through and changing nested list entries in Python

everyone. 大家。 I'm writing a simple function in Python 2.7 using the Networkx 1.9 Module for testing that my graph partitioning algorithm implementation works correctly. 我正在使用Networkx 1.9模块在Python 2.7中编写一个简单函数,以测试我的图形分区算法实现是否正常运行。 To that end, I have a list, dvecs, which has a list for each block in the partition of lists which give information about the edges from each node to the classes in the partition. 为此,我有一个列表dvecs,它在列表分区中的每个块上都有一个列表,该列表提供有关从每个节点到分区中各个类的边缘的信息。 Take a gander: a一:

#dvecs : list of len(P) lists which correspond to a list of degree vectors of each block
    numBlocks = len(P)
    dvecs = [[]] * numBlocks

    for block in P:
        blockNo = P.index(block)
        dvecs[blockNo] = [[-1] * numBlocks] * len(block)
        for node in block:
            nodeNo = block.index(node)
            for otherBlock in P:
                otherBlockNo = P.index(otherBlock)
                dvecs[blockNo][nodeNo][otherBlockNo] = len(set(nx.neighbors(G,  node)).intersection(set(otherBlock)))

The problem I'm having is that in the last line of the nested loop, the line that starts with dvec[blockNo...], according to the debugger, each of the entries in the middle-depth list(the one with indices specified by nodeNo) are being updated with the same value for each iteration of the innermost loop. 我遇到的问题是,根据调试器,在嵌套循环的最后一行中,以dvec [blockNo ...]开头的行是中间深度列表中的每个条目(带有索引的条目)对于最内部循环的每次迭代,将使用相同的值更新由nodeNo指定的值)。 In other words, it is as if 'node' is being held constant and nodeNo is iterated through all nodes in the block. 换句话说,好像“节点”保持不变,并且遍历块中的所有节点迭代了节点编号。 What is going on here? 这里发生了什么?

In response to Roman, I tried the following: 为了回应Roman,我尝试了以下方法:

for blockNo, block in enumerate(P):
        dvecs[blockNo] = [[-1] * numBlocks] * len(block)
        for nodeNo, node in enumerate(block):
            for otherBlockNo, otherBlock in enumerate(P):
                dvecs[blockNo][nodeNo][otherBlockNo] = len(set(nx.neighbors(G, node)).intersection(set(otherBlock)))

I am, however, getting the same behavior. 但是,我正在得到相同的行为。 Did I miss something? 我错过了什么?

This: 这个:

[[]] * n

gives you a list containing the same empty list, n times. 给您一个包含相同空列表的列表, n次。 So appending to any one of them appends to "all" of them — there's only one nested list. 因此,将它们追加到其中的任何一个之后,都会追加到它们的“全部”上-只有一个嵌套列表。

Try this, which will create n distinct empty lists: 试试看,这将创建n不同的空列表:

[[] for _ in range(n)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM