变量在元组中评估为False

时间:2012-12-02 14:20:30

标签: python boolean tuples transitions

为什么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\')"

另外,我不知道这些反斜杠是什么。

1 个答案:

答案 0 :(得分: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文字,并尝试返回与该输入匹配的python值。