计算平均值并平均拆分列表不起作用

2024-10-01 22:42:02 发布

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

我有一张叫做汽车的物品清单。每辆车都是一个元组,第一个元素是一个数字。我在所有汽车中找到这个数字的平均值,然后尝试将它们在中点上分成两半,使用分治算法。然而,所有的车都驶入左侧,没有一辆驶入右侧

    l = sum(car[1] for car in car)/2

    # all cars go in to this side 
    leftBeds = [car for car in cars if car[1] <= l]

    # no cars go into this side
    rightBeds = [car for car in cars if car[1] > l]

Tags: in元素goforif数字this物品
2条回答

您需要将所有车辆数量之和除以车辆数量——而不是除以2

cars = [("car 1" ,1), ("car 2",2), ("car 3",3), ("car 4",4), ("car 5",5)]

l = sum(car[1] for car in cars)/len(cars)

# all cars go in to this side 
leftBeds = [car for car in cars if car[1] <= l]

# no cars go into this side
rightBeds = [car for car in cars if car[1] > l]

print(l)
print(leftBeds,rightBeds)  

输出:

3.0
[('car 1', 1), ('car 2', 2), ('car 3', 3)] [('car 4', 4), ('car 5', 5)]

如果你想要一个中点,为什么不简单点呢

lc = len(cars)
c1,c2 = cars[:lc//2], cars[lc//2:]

首先,检查代码的第一行:

l = sum(car[1] for car in car)/2

它应该看起来像:

l = sum(car[1] for car in cars)/len(cars)

两件事:“车中有车”;如果你想要平均值,你应该用sum()除以汽车的数量

此外,任何序列(包括元组)的第一个元素的索引为[0]。如果要使用每个元组中的实际第一个元素,请将[1]替换为[0]

相关问题 更多 >

    热门问题