Python 列表之间的组合忽略和列表中的元素并忽略对的顺序

Python 列表之间的组合忽略和列表中的元素并忽略对的顺序,python,combinations,Python,Combinations,我有两份清单: list1=['a', 'z', 'd', 'e','b'] list2=['d','e', 'b' ] 我需要这两个列表元素的组合(不是排列)。我尝试了itertools.compositions和itertools.product,但我没有得到我想要的。例如,('d','d')将是错误的('a','z')也将是错误的,因为'a'和'z'属于同一个列表(list1),并且它们都不出现在list2中。最后,我不想同时使用('d','e')和('e','d')——因为顺序无关紧要

我有两份清单:

list1=['a', 'z', 'd', 'e','b']
list2=['d','e', 'b' ]
我需要这两个列表元素的组合(不是排列)。我尝试了
itertools.compositions
itertools.product
,但我没有得到我想要的。例如,
('d','d')
将是错误的<代码>('a','z')也将是错误的,因为
'a'
'z'
属于同一个列表(
list1
),并且它们都不出现在
list2
中。最后,我不想同时使用
('d','e')
('e','d')
——因为顺序无关紧要。理想的输出是:

('a','d'), ('a','e'), ('a','b'),
('z','d'), ('z','e'), ('z','b'),
('d','e'), ('d','b'), ('e','b')

编辑:通常,
list2
并不总是
list1
的子集,但我也想处理这种情况。这两个列表也可能重叠,而不是一个完整的子集。

由于顺序无关紧要,您应该使用
set
frozenset
进行顺序无关的集合

一种强力解决方案是使用
itertools.product
,但使用
set
结合列表理解来删除重复项:

from itertools import product

list1=['a', 'z', 'd', 'e','b']
list2=['d','e', 'b' ]

res = [i for i in set(map(frozenset, product(list1, list2))) if len(i) > 1]

print(res)

[frozenset({'b', 'e'}),
 frozenset({'a', 'e'}),
 frozenset({'d', 'z'}),
 frozenset({'b', 'd'}),
 frozenset({'a', 'd'}),
 frozenset({'d', 'e'}),
 frozenset({'b', 'z'}),
 frozenset({'a', 'b'}),
 frozenset({'e', 'z'})]

可能不是最有效的,但您可以尝试以下操作:

list1=['a', 'z', 'd', 'e','b']
list2=['d','e', 'b' ]

result = []
for i in list1:
    for j in list2:
        if i != j and (j,i) not in result:
            result.append((i,j))
print(result)
结果:

[('a', 'd'), ('a', 'e'), ('a', 'b'), 
 ('z', 'd'), ('z', 'e'), ('z', 'b'), 
 ('d', 'e'), ('d', 'b'), ('e', 'b')]
那么


非有效方式,但有效:

print(set([z for x in list1 for z in [tuple(x+y) if ord(x) < ord(y) else tuple(y+x) for y in list2 if x != y]]))
print(设置([z代表列表1中的x代表[tuple(x+y)如果ord(x)
{('a','e'),('e','z'),('b','z'),('d','e'),('a','b'),('b','d'),('b','e'),('d','z'),('a','d'))


我真的更喜欢@jpp解决方案

您可以通过对内部元组排序来处理
('d','e')
('e','d')
等示例:

from itertools import product

xs = ['a', 'z', 'd', 'e', 'b']
ys = ['d', 'e', 'b']

got = set(tuple(sorted(t)) for t in product(xs, ys) if t[0] != t[1])

仍然在修复('b','d')和('d','b')@SteliosM。您已经设法修复了我的无效解决方案:我错过了排序部分。谢谢
print(set([z for x in list1 for z in [tuple(x+y) if ord(x) < ord(y) else tuple(y+x) for y in list2 if x != y]]))
from itertools import product

xs = ['a', 'z', 'd', 'e', 'b']
ys = ['d', 'e', 'b']

got = set(tuple(sorted(t)) for t in product(xs, ys) if t[0] != t[1])