如何找到列表中的最大值并将最大值存储在新列表中

2024-04-25 22:36:14 发布

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

我正在努力寻找“滚动列表”的最大值,但我尝试的一切都不起作用。我不太擅长编码,老师给我的指导也不太清楚。我还必须为每个玩家重置“滚动列表”为空,我非常高兴迷糊了。求你了有人来帮忙。你知道吗


    import random
    class Player:
        def __init__(self,name ):
            self.name = name
            self.dice = []

        def __str__(self):
            return self.name
        def roll_Dice(self):
            rollDice = random.randint(1, 6)
            return rollDice

    rounds = 1
    rollList = []

    newplayer = []
    newplayer.append(Player("CAT:"))
    newplayer.append(Player("DOG:"))
    newplayer.append(Player("LIZARD:"))
    newplayer.append(Player("FISH:"))

    for rounds in range(1,4):
        print("-----------------")
        print("Round" + str(rounds))
        for p in newplayer:
            print(p)
            for x  in range (4-rounds):
                rollDice = random.randint(1, 6)
                rollList.append(rollDice) 
                print(rollList)
                max.pop(rollList)
                print(rollList)

            rollList.clear()
            len(rollList)


Tags: nameinself列表fordefrandomplayer
3条回答

这一行max.pop(rollList)毫无意义。它试图调用内置max函数的pop方法,该函数不存在。你知道吗

只需调用max本身即可获得最大值:

maxRoll = max(rollList)

如果你想删除该卷,你可以(虽然这似乎没有必要,因为你将清除列表):

rollList.remove(maxRoll)

如果要将最大值附加到另一个列表:

anotherList.append(maxRoll)

我报告了一些解决错误的建议,我想你有:AttributeError: 'builtin_function_or_method' object has no attribute 'pop'

max.pop(rollList)改成max(rollList)。你知道吗

然后只有一个元素的列表,因为您在for rounds in range(1,4):循环中调用方法,而不让列表填充其他元素。在每个循环中也调用clear。你知道吗

而且,for x in range (4-rounds):它不是必需的,它是一个嵌套循环。你知道吗

你正在打印名单而没有给每个人分配掷骰子的值,那么谁是赢家?你知道吗

最后,您将roll\u Dice()定义为Person的实例方法,为什么不使用它呢? 那么,为什么不rollList.append(p.roll_Dice())而不是:

rollDice = random.randint(1, 6)
rollList.append(rollDice)

希望这能有所帮助。你知道吗

可以使用max()函数查找列表的最大值:

mylist = [1,2,4,5,6,7,-2,3]

max_value = max(mylist)

现在最大值等于7。可以使用append()方法将其添加到新列表:

new_list = []
new_list.append(max_value)

那么新的目录将是[7]

相关问题 更多 >