2012-12-02 132 views
2

inSetStatesinInputAlphisCorrectDirection變量爲什麼進行評估,以False在下面的代碼:變量評估,以虛假的元組

class POC(object): 
    def __init__(self): 
    self.__set_states = (1,2,3,4,5) 
    self.__input_alph = ('a','b') 
    self.__directions = ('i','d') 

    def enterTransition(self): 
    while True: 
     print "enter transition tuple format:" 
     trans = raw_input(" Example (1,'a',2,'b','d') : ") 
     inSetStates = (trans[0] in self.__set_states) and (trans[2] in self.__set_states) 
     inInputAlph = (trans[1]in self.__input_alph) and (trans[3] in self.__input_alph) 
     isCorrectDirection = (trans[4].lower() in self.__directions) or (trans[4].lower() in self.__directions) 
     if (inSetStates and inInputAlph and isCorrectDirection): 
     return trans 
     break 
     else: 
     print "ERROR: Something is wrong" 

poc = POC() 
poc.enterTransition() 

調試器顯示我,three的值是False與元組(1, 'a', 2, 'b', 'd')和:

inInputAlph = False 
inSetStates = False 
isCorrectDirection = False 
self = <__main__.POC object at 0x1860690> 
trans = "(1,\'a\',2,\'b\',\'i\')" 

此外,我不知道這些反斜槓是什麼。

回答

7

trans是一個字符串,而不是元組。字符串也可以索引,所以trans[1]然後是字符串'1'(位置1處的字符)。

您需要首先將輸入轉換爲元組。一個簡單的方法,這樣做將是使用ast.literal_eval() function

>>> import ast 
>>> ast.literal_eval("(1,\'a\',2,\'b\',\'i\')") 
(1, 'a', 2, 'b', 'i') 

.literal_eval()函數把它輸入爲文字蟒蛇,並會嘗試並返回匹配該輸入一個Python值。