gpt4 book ai didi

python - 如何检查 python 类列表中的值?

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:34 25 4
gpt4 key购买 nike

你好我定义一个类person如下:

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'

最佳答案

创建一个以名字为键的字典:

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)

关于python - 如何检查 python 类列表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com