George Violettas
George Violettas

Reputation: 371

multidimensional list insertion in python

Create a list (nodes) and then create a 2-d list (nodesRTT), with the size of the nodes list. Inside the script there is code which discovers values as follows:

nodes = []
nodesRTT = [[len(nodes)]] 
if " from Node:" in line:
   pos = int(line.rpartition('Msg from Node:')[2])
if pos in nodes:
    index = nodes.index(pos) # the node already exists
else:  # node is new, just add it in the nodes list
    nodes.append(pos)#expand the array

# more search code................  

if "RTT:" in line:
    rttCur=int(line.rpartition(":")[2])
    currNode = int(line.split(':')[1])

Questions:

  1. each time the nodes list is expanded, is the nodesRTT updated too?

  2. How do I append the node's RTT data into nodesRTT? for example: nodesRTT[currNode].append(rttCur)]

Upvotes: 0

Views: 723

Answers (3)

TruBlu
TruBlu

Reputation: 523

Example of multi-dimensional array append:

nodeList = []
nodeSizeList = []

nodeOne = "nodeOne"
nodeList.append(nodeOne)
nodeSizeList.append([nodeList[0],len(nodeOne)])

print(nodeList)       # ['nodeOne']
print(nodeSizeList)   # [['nodeOne', 7]]

Upvotes: 0

Leo_28
Leo_28

Reputation: 26

From the code you have pasted, nodes list is expanded if string " from Node:" found in line and if that node not exist already. Where as nodesRTT updated only when string "RTT:" is present in line.

For second question, you can have a look at below code, you will get an idea about how to append in 2d list:

a = [[2]]
b = 3
d = []    
d.append(b) #Appending in 1d list
a.append(d) #Appending in 2d list  
print(a[0][0]) 
print(a[1][0])

Upvotes: 0

blue note
blue note

Reputation: 29081

  1. No. The expression len(nodes) is evaluated at the line it is declared. It starts being 0, and since its value is never updated by the code, it will remain zero.
  2. Instead of a 2D list, of a defaultdict(list). Then, you can directly do nodesRTT[currNode].append(rttCur)]. Since you are referring by node value, and not by position, a dict is a more appropriate data structure.

Upvotes: 1

Related Questions