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

统计列表连续相同元素出现次数,提取计数为1的对应列表元素

问题需求

统计第一个列表(lst1)中连续相同数字的出现次数,当连续出现次数为1时,提取第二个列表(lst2)中对应索引位置的元素。

给定示例数据

lst1 = [[500],[500], [500], [300], [500], [300], [300], [200]]
lst2 = [[10], [10.5], [10.7], [9], [10.1], [97], [10.2], [10.9]]

已实现的统计函数

已有trains函数可统计lst1中元素及其连续出现次数:

def trains(lst):
    element = []
    freque = []
    if not lst:
        return element
    count = 1
    for i in range(len(lst)-1):
        if lst[i][0] == lst[i+1][0]:
            count += 1
        else:
            freque.append(count)
            element.append(lst[i][0])
            count = 1
    freque.append(count)
    element.append(lst[i+1][0])

    return element,freque

print(trains(lst1)) # 输出: ([500, 300, 500, 300, 200], [3, 1, 1, 2, 1])

期望结果

最终需要得到的结果:

[[300, 9], [500, 10.1], [200, 10.9]]

解决方案实现

基于已有的trains函数,通过以下步骤得到目标结果:

  1. 调用trains函数获取元素列表和对应连续次数列表
  2. 遍历两个列表,筛选出连续次数为1的元素
  3. 计算该元素在原lst1中的索引位置,提取lst2对应位置的值并组合

实现代码如下:

def get_target_elements(lst1, lst2):
    elements, freqs = trains(lst1)
    result = []
    current_idx = 0
    for elem, freq in zip(elements, freqs):
        if freq == 1:
            # 连续次数为1,直接取当前索引对应的lst2元素
            result.append([elem, lst2[current_idx][0]])
        current_idx += freq
    return result

# 测试
print(get_target_elements(lst1, lst2)) # 输出: [[300, 9], [500, 10.1], [200, 10.9]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:11:13