Python:如何将(列表的)索引转换为integ

2024-10-01 15:33:29 发布

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

我需要从这个列表中取平均值、最小值和最大值,不使用内置函数,但它引发了一个异常:

File "<ipython-input-150-ff44c542ba16>", line 10, in problem2_8
    if temp_list[item]<lowest:

TypeError: list indices must be integers or slices, not float

这是我的代码:

^{pr2}$

Tags: 函数in列表inputifipythonlineitem
3条回答

您也可以简单地在第二个循环中迭代:

hourly_temp = [40.0, 39.0, 37.0, 34.0, 33.0, 34.0, 36.0, 37.0, 38.0, 39.0, \
               40.0, 41.0, 44.0, 45.0, 47.0, 48.0, 45.0, 42.0, 39.0, 37.0, \
               36.0, 35.0, 33.0, 32.0]

def problem2_8(temp_list):
    total=0
    for item in temp_list:
        total = total + item
    print("Average: ", total / len(temp_list))
    lowest=float('inf')  # the temporary lowest should be really big (not small)
    for item in temp_list:
        if item < lowest:
            lowest = item
    print("Low: ", lowest)

problem2_8(hourly_temp)

但是,如果您对使用内置函数sum和{}感兴趣的话,可以使这一点变得更简单:

^{pr2}$

如果python>;=3.4,也可以使用^{},而不是将和除以长度:

from statistics import mean

def problem2_8(temp_list):
    print('Average', mean(temp_list))
    print('Lowest', min(temp_list))

这相对容易解决。代码可以这样更改。在

hourly_temp = [40.0, 39.0, 37.0, 34.0, 33.0, 34.0, 36.0, 37.0, 38.0, 39.0, \
               40.0, 41.0, 44.0, 45.0, 47.0, 48.0, 45.0, 42.0, 39.0, 37.0, \
               36.0, 35.0, 33.0, 32.0]

def problem2_8(temp_list):
    total=0
    for item in temp_list:
        total=total+item
    print("Average: ",total/len(temp_list))
    lowest= temp_list[0] # Point a
    for item in temp_list: # Point b
        if item<lowest: # Point c
            lowest=item # Point d
    print("Low: ",lowest)

 problem2_8 (hourly_temp)

下面是它的工作原理的解释

a点:我不知道为什么你定义了一个low,它是一个整数,然后说lowest是low的int。我不知道为什么会这样。你实际上想要的是任意地将它设置为第一个值,这就是我所做的。在

b点:每个项目都是列表中的项目。它不是每一项的整数,它给你每个项的值

c点:既然你有这个项目的价值,你应该直接把它和最低的进行比较

d点:然后将最小值设置为新值

for item in temp_list:

返回元素而不是索引,然后只需使用以下条件:

^{pr2}$

如果要使用索引,可以使用:

for item in range(len(temp_list)):

甚至使用枚举:

for index,value in enumerate(temp_list):

另外,下次您可能希望打印出导致错误的值,看看它是否是您所期望的

相关问题 更多 >

    热门问题