简体   繁体   English

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

[英]Changing a tuple list so that the first entry is the same as the second entry

I have an example country tuple list: 我有一个示例国家元组列表:

[("GB", "Great Britain"), ("IR", "Ireland"), ("IC", "Iceland")]

For the sake of my task, I do not need the country code, only the human readable value. 为了我的任务,我不需要国家代码,只需要人类可读的值。 However Django accepts tuples in it's choiceField as such. 但是,Django在它的choiceField中接受元组。 I wrote a simple method to create a new tuple that will just contain the friendly name as both values in the tuples, eg : 我编写了一个简单的方法来创建一个新的元组,该元组将只包含友好名称作为元组中的两个值,例如:

[("Great Britain", "Great Britain"), ("Ireland", "Ireland"), ("Iceland", "Iceland")]

But i'm looking to see if there is an easier way to do this in Django or python in comparison to my implementation. 但是我正在寻找是否有比我的实现更简单的方法在Django或python中做到这一点。 Anyone have any ideas? 有人有想法么?

Method 方法

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 choice field call Django选择字段调用

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

EDIT for clarity, updated code is: 为了清楚起见,请编辑以下代码:

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 in country_list]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM