如何将项目附加到列表,使用该信息,清除列表,然后再次使用它?

时间:2015-02-27 22:16:12

标签: python list random append list-comprehension

这只是我用来尝试使游戏类似于yahtzee的代码的一部分。它可能看起来有点粗糙(这是我完成codeacademy课程后的第一个项目)。

我需要做的是将每个骰子随机选择的1-6之间的数字放入一个我可以使用的列表中,最终确定这些数字是3种类型,4种类型等等。

我只需要一种简单的方法来处理列表中的数字,然后在他们选择再次滚动后我可以删除数字并在列表中添加新的随机数。

 dice_1 = random.randrange(1,7)
 dice_2 = random.randrange(1,7)
 dice_3 = random.randrange(1,7)
 dice_4 = random.randrange(1,7)
 dice_5 = random.randrange(1,7)

 dice_list = []

 def roll_dice(): #adds random number of dice to dice_list
     dice_list.append(dice_1)
     dice_list.append(dice_2)
     dice_list.append(dice_3)
     dice_list.append(dice_4)
     dice_list.append(dice_5)

 def choice():
     player_turn = 1
     while player_turn <= 3:
        roll_again = raw_input("Would you like to roll again? (yes or no)")
        if len(roll_again) == 3:
            del dice_list[0:len(dice_list)]
            roll_dice()  #Find out how to delete what was already in that list and exchange it with the new numbers
            dice_pics()
            break
            player_turn += 1
        elif len(roll_again) == 2:
            read_dice()
            break
        else:
            print "That was not a yes or no answer! Try again!"

`

2 个答案:

答案 0 :(得分:0)

&#39;胃排空&#39;列表中的内容就像any_list = []一样简单。

答案 1 :(得分:0)

Python是一种垃圾收集语言。它为您进行内存管理。所以用五个随机骰子填充一个列表:

a = [random.randrange(1,7) for x in range(5)]

然后只是

a = []

清除它,然后根据需要再次填充它。这实际上是将名称“a”分配给新创建的空列表。现在不再引用指向的旧列表,因此将收集它。