简体   繁体   中英

List not populating at runtime in python

I am a beginner in python and am currently trying to use matplotlib to generate random values and plot them on a graph generated through matplotlib. Sad part is, to aid in generation of values and their manipulation, numPy would be a good module to help. Im not allowed to use it. Basic functions and the random module provide the data. I tried to model a measured value through randomly generated values - voltage through a wire - that constantly varies in its peak value (simulating current through a wire). So far this is what I have:

Import matplotlib.pyplot as plt
import random

def generator_2() -> int:
    return random.randint(-1, 1)
class Voltage :
    number_of_values = 200
    x=[]
    for a in range(number_of_values):
        for b in x:
            x.append(a)
    y = []
    for a in y:
        b = generator_2()
        y.append(b) 

    plt.plot(x, y, 'g')
    plt.show()

Right, so the problem I am encountering (and it might be obvious) is that the x[] and y[] lists are not populating with the generated values as the loops run. Ive debugged it enough to see that the values are populating correctly in their respective variables at runtime, but the list is not saving them? Hence, there never are any values in the lists to use with t he x and y axes.

I think you may want something like this

number_of_values = 200

x = []
y = []

for i in range(number_of_values):
    x.append(i)
    y.append(generator_2())

plt.plot(x, y, 'g')
plt.show()

The list x will contain the numbers between 0 and 200, and the list y will contain 200 randomly generated values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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