请原谅(或改进标题),但我有一个愚蠢的小问题让我非常不确定。
我有一个列表,可以包含一到两个值,不多也不少,只有这两个选项:
options = ['option one', 'option two']
正如我所说,有时列表中可能只有这些值之一,所以它可能只是 ['option two',]
其范围是网站上的简单导航。我接受查询字符串入口并在列表中搜索这些选项:
current_option = request.GET.get('option', options[0])
if not current_option in options: current_option = options[0]
如果未提供“选项”,则默认为第一个可用选项。
但是现在我想知道other选项是什么。如果 “option one”
是输入,我想要 “option two”
。例如,如果 options
列表中只有 "option one"
,我希望返回的是 False
。
我知道我可以遍历列表,但感觉应该有更好的方法来选择另一个值。
最佳答案
options.remove(current_option)
options.append(False)
return options[0]
编辑:如果不想修改options
,也可以使用可读性稍差的
return (options + [False])[current_option == options[0]]
关于Python:选择其他值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6018173/