如何在while循环中更改变量名?

时间:2015-03-12 19:46:30

标签: python-2.7

我有一个问题。我想使用while循环,而在while循环中我必须分配一个视图列表,但是它们不应该一遍又一遍地分配给同一个变量。但我不知道我必须分配多少列表。

K = 2
D = 2
while( K <= 2 or K >= 20):
    K = int(raw_input("Give the number of candidates running for speaker. "))
    if(K <= 2 or K >= 20):
        print("Sorry, wrong input.")

while(D <= 2 or D >= 1000):
    D = int(raw_input("Give the number of people who take part in the meeting. "))
    if(D <= 2 or D >= 1000):
        print("Sorry, wrong input.")

row = 1
vlist = [[]*D]
while(D > row):
    while(K < len(vlist[row-1])):
        number = int(raw_input("Give a number of a person you want to win: "))
        if(0 < number < K and number not in vlist[row-1]): 
            vlist[row-1].append(number)
        else:
            print("Sorry, wrong input, try again.")

    row += 1

这就是我现在所拥有的,但它会抛出以下错误:列表索引超出范围。我不明白为什么......

1 个答案:

答案 0 :(得分:0)

列表的第一项是空的:len(vlist[0]) 返回0,因此list[row-1]正在尝试访问-1索引的元素。