2011-05-16 75 views
4

請原諒(或改進標題),但我有一個愚蠢的小問題,這讓我很不確定。Python:選擇其他值

我有一個可以容納一到兩個值,從不多,從來沒有少,只有這兩個選項的列表:

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] 

如果沒有提供「選項」,則默認爲第一個可用的選項。

但現在我想知道什麼其他選項是。如果"option one"是輸入,我想"option two"。例如,如果options列表中只有"option one",我希望返回爲False

我知道我可以通過列表循環,但感覺就像應該有一個更好的方法來選擇其他值。

回答

10
options.remove(current_option) 
options.append(False) 
return options[0] 

編輯:如果你不想修改options,您還可以使用稍差可讀

return (options + [False])[current_option == options[0]] 
+0

+1:甚至比我的計劃更好:) – 2011-05-16 13:36:51

+1

比我的答案好得多。 :P – 2011-05-16 13:40:40

+0

第二種方法很漂亮。 – Oli 2011-05-16 15:17:13

2
current_option = request.GET.get('option', options[0]) 
if not current_option in options: 
    current_option = options[0] 
else: 
    oindex = options.index(current_option) 
    other_option = False if len(options) != 2 else options[(oindex+1) % 2]