【问题标题】:How find the max of a list and then store the max in a new list如何找到列表的最大值,然后将最大值存储在新列表中
【发布时间】:2019-06-13 20:19:17
【问题描述】:

我正在尝试找到“rollList”的最大值,但我尝试过的所有方法都不起作用。我的编码不是很好,老师给我的指导也不是很清楚。我还必须将每个玩家的“rollList”重置为空,我很困惑。请有人帮忙。

随机导入 班级球员: def __init__(self,name): self.name = 名称 自我骰子 = [] def __str__(self): 返回 self.name def roll_Dice(self): rollDice = random.randint(1, 6) 返回掷骰子 回合 = 1 滚动列表 = [] 新玩家 = [] newplayer.append(播放器(“猫:”)) newplayer.append(播放器(“狗:”)) newplayer.append(播放器(“蜥蜴:”)) newplayer.append(Player("FISH:")) 对于范围(1,4)内的回合: 打印(” - - - - - - - - -”) 打印(“轮”+ str(轮)) 对于新玩家中的 p: 打印(p) 对于范围内的 x(4 轮): rollDice = random.randint(1, 6) rollList.append(rollDice) 打印(滚动列表) 最大弹出(滚动列表) 打印(滚动列表) rollList.clear() len(滚动列表)

【问题讨论】:

  • 您希望max.pop(rollList) 行做什么?
  • 你能说明你是如何设置你使用的所有变量的吗?
  • newlst.append(max(rollList)).

标签: python list append max


【解决方案1】:

max.pop(rollList) 行毫无意义。它尝试调用不存在的内置max函数的pop方法。

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

maxRoll = max(rollList)

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

rollList.remove(maxRoll)

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

anotherList.append(maxRoll)

【讨论】:

  • @印度。您还应该发布您遇到的错误,并进行追溯。我的答案仍然成立。
【解决方案2】:

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

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

max_value = max(mylist)

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

new_list = []
new_list.append(max_value)

那么 new_list 将是 [7]

【讨论】:

    【解决方案3】:

    我报告了一些建议来解决我认为您遇到的错误: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_Dice() 作为 Person 的实例方法,为什么不使用它呢? 那么,为什么不用rollList.append(p.roll_Dice()) 而不是:

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

    希望这能有所帮助。

    【讨论】: