我有来自API的流,不断更新价格。目标是比较最后两个价格,如果x> Y然后做点什么。我可以把价格变成一个数组,然而,数组变得非常快很快..如何将元素数量限制为2,然后比较它们?
我的代码:
def stream_to_queue(self):
response = self.connect_to_stream()
if response.status_code != 200:
return
prices = []
for line in response.iter_lines(1):
if line:
try:
msg = json.loads(line)
except Exception as e:
print "Caught exception when converting message into json\n" + str(e)
return
if msg.has_key("instrument") or msg.has_key("tick"):
price = msg["tick"]["ask"]
prices.append(price)
print prices
提前感谢您的帮助!
答案 0 :(得分:2)
您可以使用deque maxlen
设置为2:
from collections import deque
deq = deque(maxlen=2)
您也可以手动检查尺寸并重新排列:
if len(arr) == 2:
arr[0], arr[1] = arr[1], new_value
答案 1 :(得分:1)
if msg.has_key("instrument") or msg.has_key("tick"):
price = msg["tick"]["ask"]
last_price = None
if prices:
last_price = prices[-1]
prices = [last_price]
if last_price > price:
#do stuff
prices.append(price)