将多个变量相互比较?

2024-05-20 14:16:49 发布

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

你好,我有一个随机的问题,这是我的第一个职位,所以我道歉,如果我的礼仪是错误的:p

我正在用python进行一场比赛,现在我有4辆车,每一轮他们都在1到10之间滚动,在这一轮之后,我想展示一些类似“carX领先,Y滚动”的东西,我不知道如何比较每辆车的滚动,并根据哪一辆是最高的打印出特定的文本。你知道吗

感谢您抽出时间


Tags: 文本错误时间职位领先礼仪每辆车carx
3条回答

所以,基本上,您正在寻找一个“argmax”实现。 这意味着你有一些N值(rolls),对应于N个索引(cars),你想找出哪个索引包含最高的值。你知道吗

不管怎样,既然你没提过,我就假设如果有几个值是最大值(几辆车的横摇相同,最高),那么第一辆车就是赢家。你知道吗

在您的例子中,给定N=4,您可以比较所有变量。这给你4个案例(每辆车赢一个),每个案例有3个比较。实际上是三个案例,因为如果前三个没有赢,那么第四个就赢了。 每个案例看起来像:

if car_1 >= car_2 && car_1 > car_3 && car_1 > car_4:
    print("Car 1 is in the lead with a roll of {}".format(car_1))

这是一种可怕的方法。所以让我们先把车列成一个清单

list_cars = [car_1, car_2, car_3, car_4]

您可以使用在numpy中定义的已经存在的argmax函数,但是让我们看看如何在没有numpy的情况下实现这一点。你知道吗

由于默认的“max”函数只提供值(roll),而不是提供值的车,因此我们将为该函数提供一个list\u cars的索引列表,以及一个表示每个索引使用相应车的值的键。所以:

func = lambda idx: list_cars[idx]
best_car = max(range(len(list_cars)), key = func)

这里的'func'定义了一个lambda函数,它为汽车列表中的每个索引返回汽车的值,range(len(list\u cars))给出了一个从0到list\u cars长度的数字列表,因此它是[0,1,2,3]。你知道吗

结果,“最佳车”将是一个介于0和3之间的数字,即值最高的车。那你就打印出来

print("Car {} is in the lead with a roll of {}".format(best_car + 1, list_cars[best_car]))

我们使用best\u car+1打印汽车的数量,因为索引从0开始计数,汽车从1开始计数。你知道吗

如果我理解的好,每轮你都要打印出领头车的名字。您可以通过创建一个汽车字典来实现这一点,其中键是汽车的名称,值是汽车的位置。每轮只更新所有车的值,并使用max()函数找到领先的车。你知道吗

示例代码:

import random

number_of_rounds = 10
cars = {'Car1': 0, 'Car2':0, 'Car3':0,'Car4':0} #dictionary of cars

for round in range(1,number_of_rounds+1):
    for car in cars:
        roll_value = random.random()*9 + 1 # get the random value from 1 to 10
        roll_value = int(roll_value) #convert to int
        cars[car] = cars[car] + roll_value
    print cars
    leading_car = max(cars, key=cars.get) # find the key with highest value
    print leading_car + " is in the lead with a roll of " + str(round)

你需要一些原始的“数据结构”来存储比赛的实际结果。 然后计算最高分+选出得分最高的选手。 将其转换为python:

from random import randint
# roll will generate numbers (uniformly) between LO,HI (HI is inclusive)
LO,HI=1,10
roll=lambda : randint(LO,HI)

n=4
# generate the participiants of the race
# here the first element is the cumulative point
parti=[[0,"car"+str(i)] for i in range(n)]
print(parti)

R=10 # num of rounds
r=0
while r<R:
  r+=1
  for i in range(n):
    parti[i][0]+=roll()
  # compute the top point
  mx=max(v[0] for v in parti)
  # select the top contestants
  top=','.join([v[1] for v in parti if v[0]==mx])
  # report the state
  print('after the {0:d}. round {1:s} on the top with {2:d} points'.format(r,top,mx))

相关问题 更多 >