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

如何将元组列表比对结果简化为单行紧凑输出格式?

解决列表元组比对输出冗余问题

问题背景

你已经将约2000行元组导入列表R,并且实现了每个元组仅与后续元组进行唯一比对,但当前输出太冗余(每个元组最多生成5行结果),需要将输出简化为单行格式:每行显示元组行号、元组内容,以及对应元素匹配到的后续元组行号(无匹配则为0)。

原比对代码

R = [(20, 12, 40, 42, 45), (40, 21, 40, 42, 49), (6, 19, 22, 36, 48), (2, 5, 20, 24, 33), (8, 12, 24, 28, 44), (3, 15, 29, 30, 37), (20, 17, 30, 33, 43), (3, 15, 16, 29, 42), (17, 18, 20, 35, 39), (20, 21, 23, 43, 48), (14, 24, 30, 40, 45)...]
for lineno1, tup in enumerate(R):
    print("")
    # iterate over the current tuple
    for i, num in enumerate(tup):
        # compare every number in the tuple to the rest of the list
        for lineno2 in range(lineno1+1, len(R)):
            tup2 = R[lineno2]
            if num == tup2[i]:
                print(f"In line: {lineno1+1} {tup} No. '{num} is found in line {lineno2+1} {tup2}.")
                break

当前输出示例

line: 1 (20, 12, 40, 42, 45) No. 20 is found in line '7' (20, 17, 30, 33, 43).
line: 1 (20, 12, 40, 42, 45) No. 12 is found in line '5' (8, 12, 24, 28, 44).
...(省略部分内容)

期望输出示例

Line 1: (20, 12, 40, 42, 45) (7, 5, 2, 2, 11) #Right side values are line numbers of the respective element in the tuple
Line 2: (40, 21, 40, 42, 49) (0, 10, 0, 0, 0)
...(省略部分内容)

解决方案代码

R = [(20, 12, 40, 42, 45), (40, 21, 40, 42, 49), (6, 19, 22, 36, 48), (2, 5, 20, 24, 33), (8, 12, 24, 28, 44), (3, 15, 29, 30, 37), (20, 17, 30, 33, 43), (3, 15, 16, 29, 42), (17, 18, 20, 35, 39), (20, 21, 23, 43, 48), (14, 24, 30, 40, 45)]

for lineno1, tup in enumerate(R):
    match_lines = []
    # 遍历当前元组的每个元素
    for i, num in enumerate(tup):
        found_line = 0
        # 只和后续元组比对
        for lineno2 in range(lineno1 + 1, len(R)):
            if num == R[lineno2][i]:
                found_line = lineno2 + 1  # 转换成人类习惯的行号(从1开始)
                break  # 找到第一个匹配就停止
        match_lines.append(str(found_line))
    # 拼接成单行输出
    print(f"Line {lineno1+1}: {tup} ({', '.join(match_lines)}) #Right side values are line numbers of the respective element in the tuple")

代码说明

  • 给每个元组初始化一个match_lines列表,用来存储每个元素对应的匹配行号(默认无匹配时为0)。
  • 对每个元素,遍历后续元组找到第一个匹配的行号就记录,没找到则保留0。
  • 最后把match_lines转换成字符串,和元组信息拼接成一行输出,完全符合你想要的简洁格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:32:36