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

两列表非完全笛卡尔积的特殊组合算法实现及数学名称问询

实现两列表的下三角式配对组合

从你的示例来看,这个组合的规则是:List1中第i个元素(索引从0开始)仅与List2中索引大于等于i的元素拼接,最终按顺序汇总所有拼接结果。这种组合可以称为下三角式配对组合(对应矩阵中下三角区域的元素配对逻辑)。

Python 实现

list1 = ['a', 'b', 'c', 'd']
list2 = ['1', '2', '3', '4']

result = []
for idx, char in enumerate(list1):
    # 遍历list2中从当前索引开始的所有元素
    for num in list2[idx:]:
        result.append(f"{char}{num}")

print(result)
# 输出: ['a1', 'a2', 'a3', 'a4', 'b2', 'b3', 'b4', 'c3', 'c4', 'd4']

C++ 实现

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<char> list1 = {'a', 'b', 'c', 'd'};
    std::vector<std::string> list2 = {"1", "2", "3", "4"};
    std::vector<std::string> result;

    for (size_t i = 0; i < list1.size(); ++i) {
        // 从当前索引i开始遍历list2
        for (size_t j = i; j < list2.size(); ++j) {
            std::string combo;
            combo += list1[i];
            combo += list2[j];
            result.push_back(combo);
        }
    }

    // 输出结果
    for (const auto& item : result) {
        std::cout << item << " ";
    }
    std::cout << std::endl;
    // 输出: a1 a2 a3 a4 b2 b3 b4 c3 c4 d4
    return 0;
}

适配不同长度的列表

如果两个列表长度不一致,只需将循环的终止条件改为取两者的最小长度即可,避免索引越界:

# Python 适配版
max_idx = min(len(list1), len(list2))
result = []
for idx in range(max_idx):
    for num in list2[idx:max_idx]:
        result.append(f"{list1[idx]}{num}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:35:29