Py学习  »  Python

python.sort()不能完全排序数字[重复]

Python_Noob • 5 年前 • 1258 次点击  

这个问题已经有了答案:

当从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

请求tickers列表中的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}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38492
 
1258 次点击  
文章 [ 1 ]  |  最新文章 5 年前
MrGeek
Reply   •   1 楼
MrGeek    6 年前

你在排序字符串,而不是数字,你的 getVolume 需要将值转换为 float 第一:

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

或者,您可以在 key 如果希望字符串由 获取音量 :

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