Python .sort()不能完全排序数字

时间:2019-05-12 22:14:43

标签: python list sorting dictionary

从API请求数据时,我会得到一个带有字典的列表,但是当我请求对它进行排序时,它并不能完全对所有数字进行排序。

我运行的代码:

def getVolume(e):
    return e["priceChangePercent"]

tickers.sort(reverse=True,key=getVolume)
for x in tickers:
    print(x["symbol"]+" "+x["priceChangePercent"])

我得到的结果:

DLTBNB 9.729
RLCBNB 9.327
BRDBNB 9.087
EVXETH 8.699
||More numbers that are being sorted correctly||DASHBNB 3.123
ARDRETH 3.093
MATICBNB 23.832
MATICUSDT 20.087
XMRETH 2.946
||Random 23 showing up that does not belong there||
BCHSVUSDC 0
NXSBTC -9.700
GASBTC -9.585
SKYBTC -9.357

在代码列表中请求dic数据时的字典示例:

{'symbol': 'ETHBTC', 'priceChange': '-0.00121400', 'priceChangePercent': '-4.363', 'weightedAvgPrice': '0.02695265', 'prevClosePrice': '0.02782400', 'lastPrice': '0.02661100', 'lastQty': '3.29400000', 'bidPrice': '0.02661100', 'bidQty': '6.70600000', 'askPrice': '0.02661900', 'askQty': '19.09500000', 'openPrice': '0.02782500', 'highPrice': '0.02841700', 'lowPrice': '0.02616300', 'volume': '320008.07300000', 'quoteVolume': '8625.06693308', 'openTime': 1557612831863, 'closeTime': 1557699231863, 'firstId': 121467734, 'lastId': 121655972, 'count': 188239}

1 个答案:

答案 0 :(得分:2)

您要对字符串而不是数字进行排序,您的getVolume首先需要将值转换为float

def getVolume(e):
    return float(e["priceChangePercent"])

或者,如果您希望key返回一个字符串,则可以在getVolume函数中进行转换:

tickers.sort(reverse = True, key = lambda x : float(getVolume(x)))