How do you create an indexable empty list in python?
Is there a way to neatly create large (i.e. indexable) empty lists in python?
This is what I am doing at the moment:
firstgen=G.neighbors(node1)
secgen=[]
thirdgen=[[],[],[],[],[],[],[],[],[],[],[]] #11 brackets because len(secgen)=11
for i in firstgen:
secgen.append(G.neighbors(i))
for i in range(len(secgen)):
for j in secgen[i]:
thirdg开发者_如何学Pythonen[i].append(G.neighbors(j))
What I am doing is finding the neighbors of the neighbors of the neighbors of an original node in a network and so my third generation list of neighbors should have the structure [ [[...],[...],[...]] , [[...],[...],[...]] , [[...],[...],[...]] ] but I am new to python and have not been able to find how to make this work without manually putting in the length of thirdgen
.
Sorry for the confusing explanation. I am doing this in order to find triads in the network i.e. if any of the third gen nodes are the same as the initial node then I have found a triad.
Thanks!
EDIT: I just realised that I can simply put thirdgen.append([])
in the first loop. Still curious about other methods though.
You don't need to create the empty lists. You can use list comprehensions to build your nested lists:
firstgen = G.neighbors(node1)
secndgen = [G.neighbors(node) for node in firstgen]
thirdgen = [[G.neighbors(node) for node in group] for group in secndgen]
firstgen: [node, ...]
secndgen: [[node, ...], ...]
thirdgen: [[[node, ...], ...], ...]
Perhaps:
thirdgen = [list() for x in range(len(secgen))]
thirdgen = [list() for x in range(11)]
Or I might be misunderstanding the actual question.
You could use list generator as follows: [[] for x in range(11)]
.
精彩评论