Python 返回文件中的变量

标签 python django variables

我有元组变量,它们是法国、德国。我试图为我的 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'),)
              }

关于Python 返回文件中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71220758/

相关文章:

python - 回合制游戏坏了

JavaScript - 变量未定义

python NameError : global name '__file__' is not defined

python - 撤消禁用 pip 缓存

python - 如何自定义登录 View

python - 如何在 Django 模板中使用 'is not None'?

arrays - 是否可以将数组元素永久存储在 Excel 中的 VBA 中?

c++ - C/C++ 或其他语言中的 SOCKS?

python - 有哪些进行机器间锁定的好方法?

python - Django:在 models.py 中 save() 期间 PositiveIntegerField 中 ManyToMany 字段的计数