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

Python如何遍历列表输出所有字符串的无重复无序二元组组合

解决方法

你需要的这种无重复元素、无序的二元配对结果,本质是求列表的2元素组合,Python里有现成的标准工具可以直接实现,也可以自己手写遍历逻辑。

方法1:使用itertools.combinations(推荐)

标准库itertools的combinations方法天然符合你的要求,返回的组合不会有同元素配对,也不会出现正反重复的排列结果:

from itertools import combinations

lst = ['A', 'B', 'C']
result = [''.join(item) for item in combinations(lst, 2)]
print(result)
# 输出:['AB', 'AC', 'BC']

方法2:手动嵌套遍历实现

如果你需要自己写遍历逻辑,只要让第二层循环永远从第一层循环的下一个下标开始取值即可:

lst = ['A', 'B', 'C']
result = []
for i in range(len(lst)):
    # 第二层从i+1的位置开始遍历,不会重复取前面的元素,自然不会生成重复组合
    for j in range(i+1, len(lst)):
        result.append(lst[i] + lst[j])
print(result)
# 输出:['AB', 'AC', 'BC']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:54:02