How do you plot a graph consisting of extracted entries from a nested list?

973 views Asked by At

I have a nested list such that;

nested_list = [[4, 3, 0], [6, 8, 7], [3, 1, 8], [2, 1, 3], [9, 9, 3],  ...] 

which has 100 entries.

I need to plot a graph of all the first elements of each sub-list where

Sub_List_1 = [4, 6, 3, 2, 9, ...] 

against all the third elements of each sub-list where

Sub_List_2 = [0, 7, 8, 3, 3, ...] 

over all the sub-lists, but I have no idea how to do this.

This is what I have tried:

k=0
while k<=100:
    x=nested_list[0][0][k]
    y=nested_list[k][0][0]
    k=+1
plt.plot(x,y)
plt.axis('image')
plt.show()

This does not work however.

1

There are 1 answers

1
Martijn Pieters On BEST ANSWER

You need to build two new lists. You can do this with list comprehensions:

x = [sub[0] for sub in nested_list]
y = [sub[2] for sub in nested_list]
plt.plot(x,y)

Your code tried to access one level of nesting too many (you can only address nested_list[k][0], not nested_list[k][0][0]) or tried to index the first value of the first nested list to index k. You also did not build new lists; you simply rebound x and y k times.