I'm trying to achieve an updating plot of random numbers, just as a learning exercise (which I can then pass real data).
I have written the following code, with the hope of ending up with a list of tuples (time and random number) which I can then split out and pass as axis to maplotlib.
def local_db_monitor(increment=10):
import datetime
import time
import random
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pylab as pl
time_list = []
while True:
now = datetime.datetime.utcnow().strftime('%H:%M:%S')
rand_number = random.randint(1,100)
time_rand = (now, rand_number)
if len(time_list) >= increment:
time_list.pop(0)
time_list.append(time_rand)
else:
time_list.append(time_rand)
items = zip(*time_list)
x_val = list(items)[0]
y_val = list(items)[1]
print(x_val, y_val)
# plt.plot(x_val, y_val)
time.sleep(0.5)
local_db_monitor()
The problem I'm having is with separating the list of tuples. I can get just the dates, or just the random numbers, but both indexes can't seem to be used at the same time.
<ipython-input-119-e33785849b16> in local_db_monitor(increment)
39
40 x_val = list(items)[0]
---> 41 y_val = list(items)[1]
42
43 print(x_val)
IndexError: list index out of range
Can someone please help me to understand what's going on here. I'm using iPython/Python 3.
You are trying to index a zip
object, in python 3 zip returns an iterator, you need to call list on items if you want to index it:
items = list(zip(*time_list))
Or use next(items)
:
items = zip(*time_list)
x_val, y_val = next(items),next(items)
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.