2017-04-17 80 views
0

说我有这个下面的代码:输入当转换为整数超出范围

command = input("prompt :> ").strip().lower() 
try: 
    command = command.split() 
# My input will be something like AB 1 2 
    x = int(command[1])-1 
    y = int(command[2])-1 
    if command[0] == "ab": 
     A_to_B(heights[x],distances[y]) 

如果高度是列表的列表,所以是距离:

heights = [['1','2'],['3','4'],['5','6']] 
distances = [['a','b'],['c','d'],['e','f']] 

所以我输入交流1 2

x = 0 
y = 1 

然后,我将从高度采集0指数列表,并从距离采集1指数列表。但是我一直在运行到IndexError:列表超出范围。我怎样才能解决这个问题?先谢谢你!

为了简单起见,我在上面的代码中更改了相当多的名字。

这里就是我的实际A_to_B函数看起来像

def tableau_to_foundation(tab, fnd): 
    '''Determines if movements from the tableaus to the foundations are valid.''' 
    if len(tab) == 0: 
     raise RuntimeError("Your tableau is empty.") 
    src_card = tab[-1] 
    dest_card = None 
    valid_fnd_move(src_card, dest_card) 
    fnd.append(tab.pop()) 

而这里的valid_fnd_move(src_card,dest_card)

def valid_fnd_move(src_card, dest_card): 
    '''Determines if the initial moves done to the foundation are valid. ''' 
    #First Check for when foundation is empty 
    if dest_card == None and src_card.rank() == 1: 
     return 
    #Second Check for when foundation is empty 
    if dest_card == None and src_card.rank() != 1: 
     raise RuntimeError("You need to place an ace into the foundation first.") 
    #Checks if foundation is not empty 
    if not dest_card.suit() == src_card.suit() and \ 
     src_card.rank == dest_card.rank() + 1: 
     raise RuntimeError("You can only place cards of the same suit together in a particular foundation") 
+0

不知道这与你的IndexError有什么关系,但你有一个第4行错字'y = int命令[2]) - 1' –

+1

我的索引错误仍然存​​在,但谢谢你的捕获 – RGPython

+0

这是Python 2还是Python 3? –

回答

0

好吧,这不是一个真正的答案,但其长期的评论:

测试代码后,我遇到了三个问题:

  1. 您应该使用的raw_input代替input否则你必须写"AB 1 2"代替AB 1 2

  2. 你在你的问题例如有一个错字:它应该是AB 1 2代替AC 1 2

  3. 由于何时有python字符串的方法是rank()? (或者你的高度和距离列表仅用于演示/哪个库介绍这个?)