我有一个来自 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
关于python - 限制附加到数组的元素数量 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32315821/