【问题标题】:Comparing a single value to multiple values from arrays in python将单个值与python中数组中的多个值进行比较
【发布时间】:2017-12-20 20:12:58
【问题描述】:

我的代码如下所示:

import requests
import re
import mechanize
import urllib
import json

htmltext = urllib.urlopen("https://www.binance.com/api/v1/klines?symbol=BCDBTC&interval=4h")

data = json.load(htmltext)

current_price= data[len(data)-1][4]
last_prices= (data[len(data)-2][4],data[len(data)-3][4],data[len(data)-4][4],data[len(data)-5][4],data[len(data)-6][4])
last_volumes= (data[len(data)-2][5],data[len(data)-3][5],data[len(data)-4][5],data[len(data)-5][5],data[len(data)-6][5])
current_volume= data[len(data)-1][5]

print current_price
print last_prices
if current_price > last_prices:
    print "the current price is greater than the last 5"
print current_volume
print last_volumes
if current_volume > last_volumes:
    print "the current volume is higher than the last 5"

但我的输出是这样的:

0.00495600
(u'0.00492500', u'0.00366300', u'0.00332800', u'0.00333800', u'0.00308000')
the current price is greater than the last 5
938.01000000
(u'29687.32500000', u'14740.03800000', u'9366.77400000', u'10324.83200000', u'44953.53400000')
the current volume is higher than the last 5

这里的问题是当前卷肯定不大于最后 5 卷,但无论如何它仍然会打印出来

我正在从这里获取数据 https://www.binance.com/tradeDetail.html?symbol=BCD_BTC

【问题讨论】:

  • 为什么不到处都是data[-2] 而不是data[len(data)-2]

标签: python arrays json web-scraping


【解决方案1】:

首先,您的数据并非全部转换为数字,其中许多是字符串格式。要将它们全部转换为浮点数,可以使用以下公式:

data = [[float(x) for x in row] for row in data]

接下来,在 if 语句中,您将一个数字与一个数字序列进行比较。您想要的是将此数字与序列中的最大数字进行比较:

if current_price > max(last_prices):
    print "the current price is greater than the last 5"

把它们放在一起:

# code to obtain data is the same

PRICE = 4
VOLUME = 5
LAST_ROW = -1

data = [[float(x) for x in row] for row in data]

current_price = data[LAST_ROW][PRICE]
current_volume = data[LAST_ROW][VOLUME]
last_prices = tuple(row[PRICE] for row in data[-6:-1])
last_volumes = tuple(row[VOLUME] for row in data[-6:-1])

print 'current_price =', current_price
print 'current_volume =', current_volume
print 'last_prices =', last_prices
print 'last_volumes =', last_volumes

if current_price > max(last_prices):
    print "the current price is greater than the last 5"

if current_volume > max(last_volumes):
    print "the current volume is higher than the last 5"

【讨论】:

  • data[-6:-1] ==> 紧接在最后一行之前的 5 行,data[-6:] ==> 最后 6 行
猜你喜欢
  • 1970-01-01
  • 2019-04-06
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多