Python 如何将列表的索引与浮点值进行比较?

Python 如何将列表的索引与浮点值进行比较?,python,Python,要迭代的嵌套列表 cost =[[125900], [115000], [105900], [85000], [150000], [155249], [97500]] 初始化变量 index = 0 cost_len = len(cost) below_avg = 0 above_avg = 0 total = 0 For循环计算成本中所有要素的总和 for i in cost: total = total + sum(i) print(total) 计算平均成本 avg

要迭代的嵌套列表

cost =[[125900], [115000],
[105900],
[85000],
[150000],
[155249],
[97500]]
初始化变量

index = 0
cost_len = len(cost)
below_avg = 0
above_avg = 0
total = 0
For循环计算成本中所有要素的总和

 for i in cost:
    total = total + sum(i)
    print(total)
计算平均成本

avg = total / len(cost)
尝试计算指数是否高于或低于平均值

for i in cost:
    while index <= cost_len:
        if i > avg:
            above_avg+=1
        elif i < avg:
            below_avg +=1
        index+=1
对于成本中的i:
而平均指数:
高于平均值+=1
elif i<平均值:
低于_平均值+=1
指数+=1

当尝试评估成本指数时,它返回“TypeError:unorderable types:list()>float()”。如何将列表的索引与变量avg进行比较?

假设每个子列表有一个元素,扁平化似乎是最好的:

flat_cost = [x[0] for x in cost]
total = sum(flat_cost)
avg = total /len(cost)
above = len([x for x in flat_cost if x > avg])
below = len([x for x in flat_cost if x < avg])
flat_成本=[x[0]表示成本中的x]
总计=总和(单位成本)
平均值=总计/长度(成本)
以上=长度([x为x,如果x>平均值,则单位成本为x])
低于=len([x为x,如果x<平均值,则为x单位成本])

如果您要处理数字列表或数字数组,我建议您使用Numpy()完成此任务:

import numpy as np

cost = np.array([[125900],
 [115000],
 [105900],
 [85000],
 [150000],
 [155249],
 [97500]])

cost-np.average(cost)

>>>array([[  6678.71428571],
       [ -4221.28571429],
       [-13321.28571429],
       [-34221.28571429],
       [ 30778.71428571],
       [ 36027.71428571],
       [-21721.28571429]])

cost-np.average(cost)
是使用Numpy广播功能的一种方法。您可以从一个数组(
cost
)中减去一个值(
np.average(cost)
),它将对整个数组进行减法,从而得到答案数组。

如果要比较每个子列表中的多个元素,则无需展平列表:

total = sum(sum(x) for x in cost)
cost_len = sum(len(x) for x in cost)
avg = total / cost_len
above = sum([sum([y > avg for y in x for x in cost])])
below = sum([sum([y < avg for y in x for x in cost])])
exact = cost_len - (above + below)
i
cost
的元素上循环,但内部
while
循环阻止它在处理
i
的第一个值后执行任何操作。请注意,
i
的值在内部循环中不会改变,因此对第一个
i
进行了反复比较,而对其他
进行了反复比较,因为
索引
到那时将是
成本+1
。要保留现有的双循环结构,可以执行以下操作:

for i in cost:
    for j in i:
        if j > avg:
            above_avg+=1
        elif j < avg:
            below_avg +=1
对于成本中的i:
对于i中的j:
如果j>平均值:
高于平均值+=1
elif j

在这一点上,您实际上不需要在最后一个代码位中使用
索引
成本
高于平均值
低于平均值
?它们从来没有被初始化过。不用担心。我收回了我的投票结果。对于每个列表中任意数量的元素,你可以用[I For j in cost For I in j]将它们展平。谢谢你,非常干净,这正是我想要的。这不是我想要的,但我会尝试用Numpy解决它,以熟悉模块,谢谢。
for i in cost:
    for j in i:
        if j > avg:
            above_avg+=1
        elif j < avg:
            below_avg +=1