Python Return 文件中的一个变量
Python Return a Variable in the file
我有法国、德国的元组变量。我正在尝试为我的 bring_cities 函数赋值,如果它是法国或德国,我希望看到法国和德国元组对象。是否有任何快捷方式可以像我在下面所做的那样不使用 if 循环?
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
cities = (('', ''),) + France + Germany
def bring_cities(country):
if country == 'France':
return France
if country == 'Germany':
return Germany
...
您可以创建字典,这样就不必为每个国家/地区编写 if 语句。您可以为此使用以下代码。
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
dictionary = {"France": France, "Germany": Germany}
def bring_cities(country):
return dictionary[country]
要使其更短,您可以在字典中定义您的国家/地区。
dictionary = {
"France": (('Paris', 'Paris'), ('Lyon', 'Lyon')),
"Germany": (('Frankfurt', 'Frankfurt'), ('Berlin', 'Berlin'),)
}
恢复 gerda 的回答
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
dictionary = {"France": France, "Germany": Germany}
def bring_cities(country):
print(dictionary[country])
user_choice = input("Enter a Country (France/Germany) and we will give you Cities in it: ")
bring_cities(user_choice)
我有法国、德国的元组变量。我正在尝试为我的 bring_cities 函数赋值,如果它是法国或德国,我希望看到法国和德国元组对象。是否有任何快捷方式可以像我在下面所做的那样不使用 if 循环?
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
cities = (('', ''),) + France + Germany
def bring_cities(country):
if country == 'France':
return France
if country == 'Germany':
return Germany
...
您可以创建字典,这样就不必为每个国家/地区编写 if 语句。您可以为此使用以下代码。
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
dictionary = {"France": France, "Germany": Germany}
def bring_cities(country):
return dictionary[country]
要使其更短,您可以在字典中定义您的国家/地区。
dictionary = {
"France": (('Paris', 'Paris'), ('Lyon', 'Lyon')),
"Germany": (('Frankfurt', 'Frankfurt'), ('Berlin', 'Berlin'),)
}
恢复 gerda 的回答
France = (
('Paris', 'Paris'),
('Lyon', 'Lyon'),
)
Germany = (
('Frankfurt', 'Frankfurt'),
('Berlin', 'Berlin'),
)
dictionary = {"France": France, "Germany": Germany}
def bring_cities(country):
print(dictionary[country])
user_choice = input("Enter a Country (France/Germany) and we will give you Cities in it: ")
bring_cities(user_choice)