get tuple list element by string name in python
我有以下tuple列表:它用于django模型中的选项字段。
1 2 3 4 | ENTITY_TYPE_CHOICES = ( (0,'choice1'), (1,'choice2'), ) |
我想按字符串名称获取选项,例如:
1 | entity_type_index = ENTITY_TYPE_CHOICES['choice1'] |
号
我得到错误:
tuple indices must be integers, not str
号
你可以通过在迭代的元组。元组对象可以只好accessed模式指数(as,not元素词典)P></
1 2 3 4 5 6 7 8 9 10 | ENTITY_TYPE_CHOICES = ( (0,'choice1'), (1,'choice2'), ) choice = 0 for i in ENTITY_TYPE_CHOICES: if i[1] =="choice1": choice = i[0] |
如果你现在打印:P></
1 | print(choice) # Output: 0 |
现在你可以使用它与
你可以在字典的建立:P></
1 2 3 4 5 6 7 8 | ENTITY_TYPE_CHOICES = ( (0,'choice1'), (1,'choice2'), ) ENTITY_TYPE_CHOICES = dict([i[::-1] for i in ENTITY_TYPE_CHOICES]) entity_type_index = ENTITY_TYPE_CHOICES['choice1'] |
输出:P></
1 | 0 |
如果你不能使用字典:P></
1 2 3 | new_choice = [i[0] for i in ENTITY_TYPE_CHOICES if i[1] == 'choice1'] print new_choice[0] |
method for You can write and find:迭代过关键元组P></
1 2 3 | get_entity_type_index(k): for index, key in ENTITY_TYPE_CHOICES: if key == k: return index |
but this is not the最佳实践方式。P></
回答:基本上ajax1234 @P></
1 2 3 4 5 6 7 8 | ENTITY_TYPE_CHOICES = ( (0,'choice1'), (1,'choice2'), ) ENTITY_TYPE_CHOICES_INDEX = {value: key for key, value in ENTITY_TYPE_CHOICES} print(ENTITY_TYPE_CHOICES_INDEX['choice2']) # output: 1 |
你可以选择使用find the index of the
然后你可以使用它给the number to接入:恩,by usingP></
1 | ENTITY_TYPE_CHOICES[ENTITY_TYPE_CHOICES.index('choice1')] |