python - 独特产品与 itertools 的组合

标签 python list permutation python-itertools

我有一个嵌套列表,想要制作两个项目的产品。

test = [[('juice', 'NOUN'), ('orange', 'FLAVOR')], 
        [('juice', 'NOUN'), ('orange', 'FLAVOR'), ('lemon', 'FLAVOR')],
        [('orange', 'FLAVOR'), ('chip', 'NOUN')]]

我期望的是这样的:

[(('juice', 'NOUN'), ('lemon', 'FLAVOR')), 
 (('juice', 'NOUN'), ('chip', 'NOUN')),
 (('orange', 'FLAVOR'), ('lemon', 'FLAVOR')),
 (('orange', 'FLAVOR'), ('chip', 'NOUN')),
 (('lemon', 'FLAVOR'), ('chip', 'NOUN'))]

也就是说,我想获得跨列表的排列,但仅限于唯一的项目。我更喜欢使用itertools。以前,我尝试过 list(itertools.product(*test)) 但我意识到它会产生嵌套列表长度的乘积...

我当前的代码:

unique_list = list(set(itertools.chain(*test)))
list(itertools.combinations(unique_list, 2))

我的思考过程是首先获取嵌套列表中的唯一项目,因此嵌套列表将是 [[('juice', 'NOUN'), ('orange', 'FLAVOR')], [('lemon', 'FLAVOR')], [('chip', 'NOUN')]],然后使用 itertools.combinations 进行排列。然而,它会在列表中排列(即果汁和橙子一起出现),这是我不希望在结果中出现的情况。

最佳答案

这可以满足您的需求,无需将原始列表的大小固定为 3:

输入:

test = [[('juice', 'NOUN'), ('orange', 'FLAVOR')], 
        [('juice', 'NOUN'), ('orange', 'FLAVOR'), ('lemon', 'FLAVOR')],
        [('juice', 'NOUN'), ('chip', 'NOUN')]]

首先,重新格式化输入以删除重复项(参见注释 1):

test = [[x for x in sublist if x not in sum(test[:i], [])] for i, sublist in enumerate(test)]

最后,获取product combinations的.

from itertools import combinations, product

for c in combinations(test, 2):
    for x in product(*c):
        print(x)

产生:

(('juice', 'NOUN'), ('lemon', 'FLAVOR'))
(('orange', 'FLAVOR'), ('lemon', 'FLAVOR'))
(('juice', 'NOUN'), ('chip', 'NOUN'))
(('orange', 'FLAVOR'), ('chip', 'NOUN'))
(('lemon', 'FLAVOR'), ('chip', 'NOUN'))
<小时/>
  1. 删除内部元组(如果它们出现在任何先前的子列表中)。这里的魔力是由 sum(test[:i], []) 完成的,它将所有先前的子列表“添加”在一起以仅执行一次成员资格检查。
<小时/>

还有一个上面的列表理解版本,用于紧凑性和风格点:

res = [x for c in combinations(test, 2) for x in product(*c)]

关于python - 独特产品与 itertools 的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53396772/

相关文章:

python - 如何在 Scipy Python 稀疏矩阵中实现 CSR_Matrix 的循环置换(左移和右移)?

python - 在python中打印两个不同列表的相同索引

Python:__str__,但对于一个类,而不是一个实例?

python - 检查连接是否已使用 Twisted 关闭

python - 连接两个不同的 mySQL 表的最佳方式——从 python 规划 django

c# - 根据 C# 中对象列表中不同属性的值组合特定属性的值?

python - 在 Python 中遍历列表列表中的列

用于排列数字列表的 Java 代码

algorithm - 最小平铺顺序

python - 用特定公式取加权平均