【问题标题】:List comprehension and "not supported between instances of 'list' and 'float"列表理解和“'list' 和 'float 实例之间不支持”
【发布时间】:2019-03-29 06:55:43
【问题描述】:

我正在尝试使用列表理解方法来查找列表中大于我的变量之一的项目。

但是,我收到以下错误消息:

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

我不知道如何绕过它。有小费吗? 这是我的程序:

def read_points():
    global alfa
    alfa = []
    alfa.append([])
    alfa.append([])
    a = 0
    b = 0
    a = float(a)
    b = float(b)
    print("Input the points, one per line as x,y.\nStop by entering an empty line.")
    while a == 0:
        start = input()
        if start == '':
            a = a + 1
            if b == 0:
                print("You did not input any points.")
        else:
            alfa[0].append(int(start.split(",")[0]))
            alfa[1].append(int(start.split(",")[1]))
            b = b + 1
    else:
        print(alfa)

def calculate_midpoint():
    midx = sum(alfa[0]) / len(alfa[0])
    global midy
    midy = sum(alfa[1]) / len(alfa[1])
    print("The midpoint is (",midx,",",midy,").")

def above_point():
    larger = [i for i in alfa if i > midy]   ###   PROBLEM IS HERE :)   ###
    number_above = len(larger)
    print("The number of points above the midpoint is", number_above)

def main():
    read_points()
    calculate_midpoint()
    above_point()

main()

【问题讨论】:

    标签: python python-3.x list typeerror


    【解决方案1】:

    alfa 是一个列表列表。

    这个:

    larger = [i for i in alfa if i > midy] 
    

    比较一个内部列表列表i 和一个浮点数midy

    不支持。这就是您的错误消息“not supported between instances of 'list' and 'float” 的确切含义。

    我会将您的坐标从两个包含所有 x 和所有 y 的内部列表加入到点列表 (x,y) 中,并过滤那些高于您的 midy 值的列表:

    points = [ (x,y) for x,y in zip(*alfa) ]
    larger = list(filter( lambda p: p[1] > midy, points)) # get all points that have y  midy
    

    【讨论】:

    • 啊,我明白了!我没有意识到在这种情况下“i”将是一个列表而不是列表中的一个项目!非常感谢,祝你有美好的一天!
    • @Astudent - 使用 print() 进行调试,或者使用允许断点在执行时检查程序的 IDE。注释掉“坏”的部分,打印它操作的东西,下次调试时仔细看看
    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 2018-03-06
    • 2020-02-12
    • 2017-09-22
    • 1970-01-01
    • 2018-05-22
    • 2020-05-05
    • 2021-03-18
    相关资源
    最近更新 更多