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

2024-04-24 06:22:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这只是我用来制作类似yahtzee的游戏代码的一部分。可能看起来有点粗糙(这是我完成代码学院课程后的第一个项目)。你知道吗

我需要做的是把随机选择的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!"

`


Tags: to代码列表lendef数字randomdice
2条回答

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

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

那就

a = []

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

“清空”列表就像any_list = []一样简单。你知道吗

相关问题 更多 >