2017-08-22 67 views
0

這段代碼對第一個runthrough運行良好,但是當它進入第二次迭代時,出現一個錯誤,指出「列表索引超出範圍」,儘管它第一個滿意時間索引需要重置嗎?列表索引超出範圍錯誤迭代

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」包含此:

紅桃A:紅心兩種:紅桃3:四心的:五心的:六心的:紅心七:心之八:心之十:心之十:心之傑:心之王:心之王:俱樂部之一:俱樂部之二:俱樂部之三:俱樂部之四:俱樂部之五:俱樂部之六:俱樂部之六:俱樂部:八個俱樂部

+0

使用for循環時,這段代碼會更清晰:'對於範圍內的pile_counter(4)' – bendl

+0

粘貼所有錯誤追蹤,以便我們可以看到哪一行導致錯誤。還提供了一個可重複的示例 – MedAli

+0

請提供一個最小,完整,可驗證的示例(https://stackoverflow.com/help/mcve)。提供的代碼看起來不完整。 – tdube

回答

2

在諸如cards= [pile_one+ pile_two+pile_three]這樣的行中,您正在創建一個僅包含一個元素的新列表,該元素是一個列表。所以你得到的東西是這樣的:的

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

您可以使用cards = pile_one + pile_two + pile_three做你想要什麼。

相關問題