2015-02-12 12 views
5

listesinde saklanır. Python'da lst listesinde saklanan nesneler var. Bir nesne olarak sadece bir nesne özniteliğini çizmem gerekiyor. Python nesnesi niteliğini ve nesnelerini çizme

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

Bunu denedim ve çalışıyor, ama çok 'pythonic' yol değildir düşünüyorum:

temp = [] #any better idea? 
for x in range(0,len(lst)): 
    temp.append(l[x].value) 
plt.plot(temp, 'ro') 

sen önermek ne, nasıl daha pythonic bir şekilde plit için? Teşekkür ederiz

cevap

2

Değerlerinizin bir listesini oluşturmak için list comprehension'u kullanın.

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

liste anlama aşağıdaki kodu eşdeğerdir:

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

Not olduğunu yapabildin başka liste anlama

lst = [(Particle(value=np.random.random_integers(10), weight=1) for _ in range(10)] 
ile lst koleksiyonunun kadar da düzenli oluşturma
İlgili konular