限制附加到数组的元素数量 - Python
Limit the number of elements appended to array - Python
我有一个来自 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
在此先感谢您的帮助!
您可以使用 deque 并将 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)
我有一个来自 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
在此先感谢您的帮助!
您可以使用 deque 并将 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)