python - 限制附加到数组的元素数量 - Python

标签 python arrays stream limit

我有一个来自 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

预先感谢您的帮助!

最佳答案

您可以使用dequemaxlen 设置为 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/

相关文章:

python - 线程不工作

连接 char 数组和 char

java - BufferedReader 将什么字符解释为流的结尾?

python - 使用 Sphinx 通过命令行参数记录脚本时出现异常

python - 如何在组内逐条查找唯一值?

python - 如何为 Sphinx 自定义模块名称

c - 指向 char[2][2] 数组的 10 指针数组

c - 在C中解析 "String"(字符数组)为字符串,int和int

c# - C# 中的错误 "This stream does not support seek operations"

Java自定义输入输出流