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

从元组列表中提取以1起始的非0数值序列及对应字符

提取以1起始的非0数值及对应字符序列

给定元组列表:

a = [('a', 0), ('c', 1), ('d', 0), ('b', 1), ('t',1), ('j',2), ('k',3), ('s', 4), ('l',1), ('y',1), ('r',2), ('b',3), ('k',4)]

需求说明:

  1. 过滤掉所有值为0的元组
  2. 将剩余元素分组为多个子序列,每个子序列以1开头;仅当遇到出现在大于1的数值之后的1时,才开启新子序列
  3. 分别输出分组后的数值序列和对应的字符序列

实现代码

a = [('a', 0), ('c', 1), ('d', 0), ('b', 1), ('t',1), ('j',2), ('k',3), ('s', 4), ('l',1), ('y',1), ('r',2), ('b',3), ('k',4)]

# 过滤值为0的元组
filtered = [item for item in a if item[1] != 0]

num_sequences = []
char_sequences = []
current_nums = []
current_chars = []

for char, num in filtered:
    if num == 1:
        # 若当前已有序列且最后一个数值大于1,开启新序列
        if current_nums and current_nums[-1] > 1:
            num_sequences.append(current_nums)
            char_sequences.append(current_chars)
            current_nums = [num]
            current_chars = [char]
        else:
            current_nums.append(num)
            current_chars.append(char)
    else:
        # 非1数值直接加入当前序列
        current_nums.append(num)
        current_chars.append(char)

# 加入最后一个未保存的序列
if current_nums:
    num_sequences.append(current_nums)
    char_sequences.append(current_chars)

# 输出结果
print("数值序列:", num_sequences)
print("字符序列:", char_sequences)

代码说明

  1. 过滤0值:通过列表推导式快速筛选出非0元素,得到待处理的干净序列。
  2. 分组逻辑:遍历过滤后的序列,维护当前正在构建的子序列:
    • 遇到数值为1时,判断当前序列的最后一个数值是否大于1:若是,说明需要开启新序列,保存当前序列并重置;否则将当前元素加入现有序列。
    • 遇到非1数值时,直接追加到当前序列中。
  3. 收尾处理:循环结束后,将最后一个未保存的子序列加入结果列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:27:20