【问题标题】:How the get N highest numbers?如何获得N个最高的数字?
【发布时间】:2021-01-14 08:11:10
【问题描述】:

我有这个代码,我必须得到一个答案,它会从 'r' 变量中返回每个 percent_change_24h 的 10 个最高数字。我应该使用什么方法?我见过 max 方法,但那个方法只返回一个值(最高肯定,但只有一个)

   url='https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

params={
    'start':'1',
    'limit':'100',
    'convert':'USD'
}

headers={
    'Accepts':'applications/json',
    'X-CMC_PRO_API_KEY':'b8ee0ea1-ae9b-44ab-9132-02e6e5430eb1'
}

#data= requests.get(url=url,headers=headers,params=params).json()
#pprint(data)`

r= requests.get(url=url,headers=headers,params=params).json()
currencies=[]

for currency in r['data']:
    if currency['quote']['USD']['percent_change_24h']>1:
        currencies.append(
            currency['symbol']
        )

pprint(max(currencies))

【问题讨论】:

  • 您可以在currencies 列表上使用sort()sorted() 函数,然后打印此列表中的前10 项。
  • print(sorted(currencies, reverse=True)[:10])

标签: python bots pycrypto cryptoapi


【解决方案1】:
from heapq import nlargest

print(nlargest(n, currencies))

【讨论】:

    【解决方案2】:

    由于您已将货币值存储在列表中。您可以先按降序排列: sorted = currencies.sort(reverse=True) 然后下面将从您的列表中给出您的 N 最大值。 print(sorted[-N:])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 2016-03-17
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多