Building attribute and python object objects is stored in a list

I have objects stored in a list named lst in python. I need to build only one attribute of objects as a graph.

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 this is not a 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 use it in a more pythonic way? Thanks you

+5
source share
1 answer

Use the list description to create 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() 

enter image description here

Understanding the list is equivalent to the following code:

 values = [] for x in lst: values.append(x.value) 

Please note that you can also remove the creation of your lst collection with a different list comprehension

 lst = [(Particle(value=np.random.random_integers(10), weight=1) for _ in range(10)] 
+2
source

Source: https://habr.com/ru/post/1213232/


All Articles