5

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

1 Answer 1

2

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()

enter image description here

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)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.