我正在尝试找到一种方法来列出有关用户的信息并显示有关他们感兴趣的城市的事实。如果列出的城市在城市词典中,则我想显示有关该城市的事实。我对Python还是很陌生,对这个问题有些困惑。
class Ativo:
def __init__(self,nome = "",qtd_total=0,pm=0):
self.nome = nome
self.qtd_total = qtd_total
self.pm = pm
for asset in set_ativo: #set_ativo is the SET with all objects to be created
asset = Ativo(nome=asset) #Assuming that the first on the list is called BIDI
print(asset.nome) #this works
print(asset.qtd_total) #this works
print(BIDI.nome) #THIS DOES NOT WORK -- > NameError: name 'BIDI' is not defined
print(BIDI.nome) #THIS DOES NOT WORK ---> NameError: name 'BIDI' is not defined
答案 0 :(得分:0)
for place in favorite_places['zac']:
if place in cities:
print(cities[place])
这应该有效。您要做的只是在favorite_places
列表上循环,但是该列表位于词典中,因此要访问它,您需要在favorite_places
处索引词典zac
,因为这是名称对应于列表值的键。因此,您可能想遍历favorite_places['zac']
。
在第一个for循环中,变量place
现在将分配给favorite_places['zac']
中的每个位置。然后,您要检查当前的place
是否在城市词典中。您可以通过编写if place in cities
来实现。如果是这样,则打印信息,否则什么也不做。
答案 1 :(得分:0)
以下一些指针可以帮助您:
.format
是一种字符串方法,因此您需要在字符串上调用format,
不在print
上。cities
字典就可以直接
如果城市像这样cities.get(place)
存在,请进行查找。for name, places in favorite_places.items():
print("\n {}'s favorite places are:".format(name.title()))
print("{}".format(places))
for place in places:
if cities.get(place):
print("\n Here are so facts about {}:".format(place.title()))
print(cities[place])
答案 2 :(得分:0)
尝试一下
for user in favorite_places:
print(user)
for place in favorite_places[user]:
if place in cities:
print(cities[place])