尝试创建过滤器但出现类型错误

时间:2020-10-13 04:22:58

标签: python

我正在尝试使过滤器返回列表中所有大于列表平均值的数字:

import math

print("Example of filter")

x=[5,1,10,30,5,13,5,19,-58,100,-5,-23,0,32,12,13,4,19]

avg = sum(x) / len(x) #Finding the average of the numbers in x.

print(avg)

if avg>x:
   print(x)

但是我在下面出现此错误:

TypeError: '>' not supported between instances of 'float' and 'list'

3 个答案:

答案 0 :(得分:1)

avgint类型,而x是列表类型。将int与列表进行比较会给您带来错误。

您需要遍历列表x,并检查其元素是否大于avg

您可以这样做

 result = [i for i in x if i>avg]
 print(result)

 result = []
 for val in x:
     if val>avg:
         result.append(val)
 print(result)

答案 1 :(得分:0)

import math

print("Example of filter")

x=[5,1,10,30,5,13,5,19,-58,100,-5,-23,0,32,12,13,4,19]

avg = sum(x) / len(x) #Finding the average of the numbers in x.

print(avg)

result = []

for i in x:
    if avg < i:
       result.append(i)

print(result)

这有效。

enter image description here

我认为这是您想要的输出。使用for循环附加大于平均值的值。希望对您有所帮助!?

答案 2 :(得分:0)

您可以为此目的使用numpy并从loop中拯救自己

import numpy as np

x=[5,1,10,30,5,13,5,19,-58,100,-5,-23,0,32,12,13,4,19]
x = np.array(x) #convert list to numpy array
avg = np.mean(x)
result = x[x>avg] 
result = list(result) #convert numpy array to list

输出

[30, 13, 19, 100, 32, 12, 13, 19]