2015-11-16 62 views
1

你好,我定義一個類人如下:如何檢查python中的類列表中的值?

class Person(object): 
    def __init__(self, X, Y): 
     self.name = X 
     self.city = Y 
names = ['Bob', 'Alex', 'John'] 
cities = ['New York', 'London', 'Rome'] 
N = list() 
for i in range(0,3): 
    x = names[i] 
    y = cities[i] 
    N.append(Person(x,y)) 

我想自動檢查名稱的對應城市,像這樣

N.name['Bob'].city = 
'New York' 
+1

不可能有類(以當前形式)。如果存在一對一關係(或一對多關係),則考慮使用字典。 – hjpotter92

回答

2

創建一個名爲密鑰的字典:

class Person(object): 
    def __init__(self, name, city): 
     self.name = name 
     self.city = city 
names = ['Bob', 'Alex', 'John'] 
cities = ['New York', 'London', 'Rome'] 

persons = {n: Person(n,c) for n,c in zip(names, cities)} 

print(persons['Bob'].city) 
2

使用Python字典

people = {} 
names = ['Bob', 'Alex', 'John'] 
cities = ['New York', 'London', 'Rome'] 
if len(names) != len(cities): 
    # You might want to do something other than a base exception call here 
    raise Exception('names and cities must be of equal size') 
for i in range(len(names)): 
    people[names[i]] = cities[i] 
print(people['Bob']) 

>>>'New York'