python - 更改元组列表,使第一个条目与第二个条目相同

标签 python django

我有一个示例国家/地区元组列表:

[(“GB”、“英国”)、(“IR”、“爱尔兰”)、(“IC”、“冰岛”)]

为了完成我的任务,我不需要国家/地区代码,只需要人类可读的值。然而,Django 在它的 choiceField 中接受元组。我编写了一个简单的方法来创建一个新元组,该新元组仅包含友好名称作为元组中的两个值,例如:

[("英国", "英国"), ("爱尔兰", "爱尔兰"), ("冰岛", "冰岛")]

但我想看看与我的实现相比,在 Django 或 python 中是否有更简单的方法来做到这一点。大家有什么想法吗?

方法

def change_country_tuples(country_list):
    new_country_list = []
    for country in country_list: 
        new_country_list.append(tuple((country[1], country[1])))
    return new_country_list

Django 选择字段调用

country = fields.ChoiceField(
    label='Choose country',
    choices=[('', 'Select a country')] + change_country_tuples(country_choices),
)

编辑 为了清楚起见,更新的代码是:

def change_country_tuples(country_list):
    return [(country_name, country_name) for country_code, country_name in country_list]

最佳答案

在 python 中,changeCountryTuples 可以在一行中完成,如下所示:

newCountryList = [(country[1],country[1]) for Country_list]

关于python - 更改元组列表,使第一个条目与第二个条目相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54181329/

相关文章:

python 魔杖 : composite image with transparency

python - 如何使用张量初始化内核

python - 我可以在 django 模型字段中添加帮助文本吗

django - 为 django 应用程序提供服务时出现 uwsgi 段错误

javascript - 如何在 Django 中 AJAX 视频上传

python - Gunicorn 有多个 worker : Is there an easy way to execute certain code only once?

python - Sympy coeff 与 as_independent 不一致

python - 为什么这个特定的网站在解析时会导致递归错误?

django - 如何在没有模板的情况下从 django View 模拟 HTTP Post 请求

python - 如何使用 django admin 在数据库中插入记录后添加函数?