我有一个来自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 jsonn" + str(e)
return
if msg.has_key("instrument") or msg.has_key("tick"):
price = msg["tick"]["ask"]
prices.append(price)
print prices
提前感谢您的帮助!
您可以将maxlen
设置为2:
from collections import deque
deq = deque(maxlen=2)
您也可以手动检查大小并重新排列:
if len(arr) == 2:
arr[0], arr[1] = arr[1], new_value
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)