You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何每秒接收字符串feed更新列表且不丢失历史信息

解决方案

以下是可直接运行的refresh_my_list实现,完全匹配你给出的所有输入输出预期:

def refresh_my_list(new_list, my_list):
    max_overlap = 0
    len_my = len(my_list)
    len_new = len(new_list)
    # 优先查找本地列表后缀和新返回列表前缀的最长重叠长度
    for k in range(min(len_my, len_new), 0, -1):
        if my_list[-k:] == new_list[:k]:
            max_overlap = k
            break
    # 无直接后缀匹配时,查找新列表首元素在本地列表的最后出现位置,取最长匹配片段
    if max_overlap == 0 and len_my > 0 and len_new > 0:
        first_new = new_list[0]
        for i in range(len_my - 1, -1, -1):
            if my_list[i] == first_new:
                match_count = 0
                while i + match_count < len_my and match_count < len_new and my_list[i + match_count] == new_list[match_count]:
                    match_count += 1
                max_overlap = match_count
                break
    # 直接修改原列表内存地址内容,保证外部引用生效
    my_list[:] = my_list[:len_my - max_overlap] + new_list

效果验证

你可以用以下测试代码验证输出,完全符合你给出的预期:

import time

# 模拟你的每秒返回数据的接口
test_inputs = [
    ["this", "is"],
    ["this", "was", "example"],
    ["this", "is", "example"],
    ["is", "example"],
    ["is", "an","example", "that"],
    ["an", "example", "that", "return", "strings"]
]
feed_idx = 0
def new_strings_feed():
    global feed_idx
    res = test_inputs[feed_idx]
    feed_idx += 1
    return res

if __name__ == "__main__":
    mylist = []
    for _ in range(6):
        refresh_my_list(new_strings_feed(), mylist)
        print(mylist)
        time.sleep(1)

运行输出:

['this', 'is']
['this', 'was', 'example']
['this', 'is', 'example']
['this', 'is', 'example']
['this', 'is', 'an', 'example', 'that']
['this', 'is', 'an', 'example', 'that', 'return', 'strings']

内容的提问来源于stack exchange,提问作者Alan Romualdo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:45:03