类型不可排序:过滤生成器表达式中的str() > float()时

2024-10-01 04:46:30 发布

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

我的代码一直工作正常,突然出现了以下错误:

unorderable types: str() > float() 

enter image description here

我通过API提取订单簿,然后希望获得金额大于1的所有订单。你知道吗

filtermaxxamount = (x for x in dic if x['max_amount'] > 1)

这似乎是一个“生成器”类。 然后我想从filtermaxxamount中提取最高价格:

highestprice = ((max((x for x in filtermaxxamount if x['min_amount'] < 1), 
                     key=lambda x:x['price']))['price'])

在这之后,我得到了上面提到的错误。 以前一切都很顺利,我也没有任何问题。API没有改变,我在网站上查过。你知道吗

我犯了什么错误? 有什么问题?它一定是一本字典而不是一个生成器,对吗?你知道吗


Tags: 代码in订单apiforif错误float
1条回答
网友
1楼 · 发布于 2024-10-01 04:46:30

您似乎已从Python2切换到Python3。你知道吗

在Python 2中,所有的type都可以排序:

print(sorted( [1,"2",3,"None"]`))  
# Output: [1,3,'2','None'] 

Python 3中,情况不再是这样:

print(sorted( [1,"2",3,"None"]`))  
# TypeError: '<' not supported between instances of 'str' and 'int' 

# workaround for sorting: use an explicit key function
print(sorted( [1,"2",3,"None"], key=lambda x: 999999999999 if isinstance(x,str) else x))

Why is the order of types in Python 2 fixed, and an unorderable TypeError in Python 3?


要解决您的问题:(除了dupe建议之外,我还回答了原因)

将元素筛选为具有浮点值和非字符串的元素:

l = [ {'max_amount' : 33.0}, {'max_amount' : -33.0}, {'max_amount' : 12.6},
      {'max_amount' : "None"}, {'max_amount' : "34"}]

try:
    # only look at those that are floats (seperated for clarity)
    filter_float = (x for x in l if isinstance(x['max_amount'],float))

    # from those filter the > 1 ones
    filtermaxxamount = (x for x in filter_float if x['max_amount'] > 1)

    # creates an error:
    # filtermaxxamount = (x for x in l if x['max_amount'] > 1)
    print(*filtermaxxamount) 
except TypeError as e:
    print(e)  # never reached unless you uncomment # filtermaxxamount = (x for x in l ...

输出:

{'max_amount': 33.0} {'max_amount': 12.6}

相关问题 更多 >