【问题标题】:How to find min/ max value and create a list (python)如何找到最小值/最大值并创建一个列表(python)
【发布时间】:2020-04-16 06:20:57
【问题描述】:

请忽略我未使用的导入!

我试图创建一个列表来查找“pa_walk”的最小值和最大值,但我只是想出如何去做,每次我尝试它都会说错误。

import random
from math import sqrt
from math import hypot
import statistics


random.seed(20190101)

def takeOnePaStep():
    direction = random.randint(0,3)
    if direction == 0:
        return (0,1)
    elif direction == 1:
        return (1,0)
    elif direction == 2:
        return (0,-1)
    elif direction == 3:
        return (-1,0)


def randomWalkPa(steps):
    pa = [0,0]
    for _ in range (steps):
        nextStep = takeOnePaStep()
        pa[0] += nextStep[0]
        pa[1] += nextStep[1]
    pasDistance = hypot(pa[0],pa[1])
    return pasDistance

 #   paMean = statistic.mean(distance)

steps = int(input("Please enter the number of steps: "))
tries = int(input("How many times should I perform the experiment? "))

for _ in range(tries):
    pa_walk= randomWalkPa(steps)
    print(pa_walk)

【问题讨论】:

  • 你遇到了什么错误?
  • 浮点对象不能被解释为整数

标签: python tuples max min minmax


【解决方案1】:


我猜这是因为您的函数 randomWalkPa(steps) 返回距离的浮点数,这就是为什么您首先需要创建一个列表(在下面的示例中,我刚刚创建了 pa_walk 一个列表。在您的 for 循环中只需 .append每次尝试到该列表的距离。最后你可以调用内置函数max()min()来获得最大和最小距离。我取消了最小和最大调用的打印命令,只得到一次结果

pa_walk = []
for _ in range(tries):
    pa_walk.append(randomWalkPa(steps))

print(f"The Maximum Distance reached was: {max(pa_walk)}, in trial: {pa_walk.index(max(pa_walk))}")
print(f"The Minimum Distance reached was: {min(pa_walk)}, in trial: {pa_walk.index(min(pa_walk))}")

在 cmets 推荐后,这里是完整代码(我只更改了最后 5 行)

import random
from math import sqrt
from math import hypot
import statistics


random.seed(20190101)

def takeOnePaStep():
    direction = random.randint(0,3)
    if direction == 0:
        return (0,1)
    elif direction == 1:
        return (1,0)
    elif direction == 2:
        return (0,-1)
    elif direction == 3:
        return (-1,0)


def randomWalkPa(steps):
    pa = [0,0]
    for _ in range (steps):
        nextStep = takeOnePaStep()
        pa[0] += nextStep[0]
        pa[1] += nextStep[1]
    pasDistance = hypot(pa[0],pa[1])
    return pasDistance

 #   paMean = statistic.mean(distance)

steps = int(input("Please enter the number of steps: "))
tries = int(input("How many times should I perform the experiment? "))

pa_walk = []
for _ in range(tries):
    pa_walk.append(randomWalkPa(steps))

print(f"The Maximum Distance reached was: {max(pa_walk)}, in trial: {pa_walk.index(max(pa_walk))}")
print(f"The Minimum Distance reached was: {min(pa_walk)}, in trial: {pa_walk.index(min(pa_walk))}")


编辑:
需要注意的一点是,在 python 中,使用下划线而不是驼峰式是惯例。这意味着函数randomWalkPa() 最好称为random_walk_pa()。这不是使代码正常工作所必需的,完全取决于您

【讨论】:

  • 你可能想放完整的代码,发布问题的那个似乎在 python 中没有经验
猜你喜欢
  • 2011-02-18
  • 2012-04-18
  • 2018-08-06
  • 2018-03-12
  • 2020-03-08
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多