我有一个示例国家/地区元组列表:
[(“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/