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

2024-06-28 20:24:22 发布

您现在位置: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 = 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

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


Tags: in元素列表forindexlen指数below
3条回答

如果您要处理数字列表或数字数组,那么我建议您使用Numpy(http://docs.scipy.org/doc/numpy/user/index.html)执行此任务:

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)

关于这个解决方案有两点:

  1. totalcost_len的计算使用生成器,而不是根据结果创建列表。由于中间结果不需要额外的存储,因此这可以节省一些内存和可能的执行时间。你知道吗
  2. abovebelow是嵌套生成器,基本上相当于您尝试执行的嵌套循环。你知道吗

下面是对最终嵌套循环的作用和修复方法的说明:

for i in cost:
    while index <= cost_len:
        if i > avg:
            above_avg+=1
        elif i < avg:
            below_avg +=1
        index+=1

icost的元素上循环,但是内部的while循环阻止它在处理i的第一个值之后执行任何操作。注意,i的值在内部循环中没有改变,因此第一个i的比较是反复进行的,其他的则完全没有,因为index到那时将是cost_len + 1。要保留现有的双循环结构,可以执行以下操作:

for i in cost:
    for j in i:
        if j > avg:
            above_avg+=1
        elif j < avg:
            below_avg +=1

在这一点上,您并不真正需要index。你知道吗

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

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])

相关问题 更多 >