列表索引超出范围错误与迭代

时间:2017-08-22 14:08:37

标签: python list python-3.5

这段代码在第一次运行时运行良好,但是当它进入第二次迭代时,出现错误,显示“列表索引超出范围”,尽管它第一次对它感到满意。索引是否需要重置?

    while pile_counter < 3:
        pile_one= operator.itemgetter(0,3,6,9,12,15,18)(cards)
        pile_two= operator.itemgetter(1,4,7,10,13,16,19)(cards)
        pile_three= operator.itemgetter(2,5,8,11,14,17,20)(cards)
        print("pile one is", pile_one, "pile two is", pile_two, "pile three is", pile_three)
        user_pile= input("which pile is your card in? ")
        ##check one two or three
        if user_pile== "one":
            cards= [pile_two+ pile_one + pile_three]
        elif user_pile== "two":
            cards= [pile_one+ pile_two+pile_three]
        else:
            cards=[pile_one+ pile_three+ pile_two]
        print(cards)
        pile_counter= pile_counter+ 1


The full code runs like this:



    import random
    import operator
    def cards_random_shuffle():
            with open('cards.txt') as f: 
                for word in f:
                    cards = word.strip().split(":")
            random.shuffle(cards)
            return cards
    #print(cards_random_shuffle()) 
    cards= cards_random_shuffle()

    def cards_sort(cards):
        pile_counter= 0
        while pile_counter < 3:
            pile_one= operator.itemgetter(0,3,6,9,12,15,18)(cards)
            pile_two= operator.itemgetter(1,4,7,10,13,16,19)(cards)
            pile_three= operator.itemgetter(2,5,8,11,14,17,20)(cards)
            print("pile one is", pile_one, "pile two is", pile_two, "pile three 
is", pile_three)
            user_pile= input("which pile is your card in? ")

            if user_pile== "one":
                cards= [pile_two+ pile_one + pile_three]
            elif user_pile== "two":
                cards= [pile_one+ pile_two+pile_three]
            else:
                cards=[pile_one+ pile_three+ pile_two]
            print(cards)
            pile_counter= pile_counter+ 1
    print(cards_sort(cards))

文件“cards.txt”包含:

心中的两个:心中的两个:心中的三个:心中的四个:心中的五个:心中的七个:心中的七个:心中的八个:心中的九个:心中的十个:心中的杰克:心中的女王:心之王:俱乐部之王:两个俱乐部:三个俱乐部:四个俱乐部:五个俱乐部:六个俱乐部:七个俱乐部:八个俱乐部

1 个答案:

答案 0 :(得分:2)

cards= [pile_one+ pile_two+pile_three]之类的行中,您创建的新列表只包含一个元素,即列表。所以你得到这样的东西:

[[card1, card2, ...]]代替[card1, card2, ...]

您可以使用cards = pile_one + pile_two + pile_three做您想做的事。