I have objects stored in list called lst in python. I need to plot just one objects attribute as a plot.
import numpy as np
import matplotlib.pyplot as plt
class Particle(object):
def __init__(self, value = 0, weight = 0):
self.value = value
self.weight = weight
lst = []
for x in range(0,10):
lst.append(Particle(value=np.random.random_integers(10), weight = 1))
I tried this and it works, but I think it is not very 'pythonic' way:
temp = [] #any better idea?
for x in range(0,len(lst)):
temp.append(l[x].value)
plt.plot(temp, 'ro')
what do you suggest, how to plit it in more pythonic way? Thank you
Use a list comprehension to generate a list of your values.
import numpy as np
import matplotlib.pyplot as plt
class Particle(object):
def __init__(self, value = 0, weight = 0):
self.value = value
self.weight = weight
lst = []
for x in range(0,10):
lst.append(Particle(value=np.random.random_integers(10), weight = 1))
values = [x.value for x in lst]
plt.plot(values, 'ro')
plt.show()
The list comprehension is equivalent to the following code:
values = []
for x in lst:
values.append(x.value)
Note that you could also tidy up the creation of your lst
collection with another list comprehension
lst = [(Particle(value=np.random.random_integers(10), weight=1) for _ in range(10)]
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.