在for循环中使用append来填充列表

时间:2017-10-04 05:20:03

标签: python

我试图编写一个基本的牌组改组程序,但当我尝试在我的牌组列表中调用任何特定索引时,反复出现越界错误。

suits = ["spades", "diamonds", "hearts", "clubs"] 

deck = []
def createDeck(deck):
    for i in range(0,4):
        for j in range(0,13):
            c = str(j+1) + " of " + suits[i]
            return deck.append(c)

3 个答案:

答案 0 :(得分:1)

在所有循环之后,您应该返回名为“deck”的列表。

suits = ["spades", "diamonds", "hearts", "clubs"] 
deck = []
def createDeck(deck): 
    for i in range(0,4): 
        for j in range(0,13): 
            c = str(j+1) + " of " + suits[i] 
            deck.append(c)
    return deck

答案 1 :(得分:0)

suits = ["spades", "diamonds", "hearts", "clubs"]
deck = [] 
def createDeck(deck):
    for i in range(0,4):
        for j in range(0,13):
            c = str(j+1) + " of " + suits[i]
            return deck.append(c)

假设这就是你所拥有的,你的deck []将只包含一个项目,因为你在for循环的第一步中从函数返回。失去了回报和你的好处。

答案 2 :(得分:0)

如果你想要没有先前套装元素的套牌列表,那么在函数中定义套牌,否则当你将套装作为参数传递时,套牌将成为套装列表。

   suits = ["spades", "diamonds", "hearts", "clubs"]


    def createDeck(deck):
        deck=[]

        for i in range(0,4):
            for j in range(0,13):
                c = str(j+1) + " of " + suits[i]

                deck.append(c)
        return deck

    print(createDeck(suits))

输出:

['1 of spades', '2 of spades', '3 of spades', '4 of spades', '5 of spades', '6 of spades', '7 of spades', '8 of spades', '9 of spades', '10 of spades', '11 of spades', '12 of spades', '13 of spades', '1 of diamonds', '2 of diamonds', '3 of diamonds', '4 of diamonds', '5 of diamonds', '6 of diamonds', '7 of diamonds', '8 of diamonds', '9 of diamonds', '10 of diamonds', '11 of diamonds', '12 of diamonds', '13 of diamonds', '1 of hearts', '2 of hearts', '3 of hearts', '4 of hearts', '5 of hearts', '6 of hearts', '7 of hearts', '8 of hearts', '9 of hearts', '10 of hearts', '11 of hearts', '12 of hearts', '13 of hearts', '1 of clubs', '2 of clubs', '3 of clubs', '4 of clubs', '5 of clubs', '6 of clubs', '7 of clubs', '8 of clubs', '9 of clubs', '10 of clubs', '11 of clubs', '12 of clubs', '13 of clubs']