从子列表中获取所有对,而没有一个对仅来自一个子列表

时间:2018-07-20 20:23:13

标签: python list itertools

我有许多带有一堆元素的列表,

lists = [
    ["a", "b", "c"],
    [7, 1, 2, 3, 5],
    ["alpha", "gamma"],
    # ...
]

我现在想创建一个上述列表中所有单独元素对的列表,即

combinations = [
    ["a", 7],
    ["a", 1],
    # ...
    ["c", "gamma"],
    [7, "alpha"],
    # ...
]

,条件是该对中的两个元素都来自不同的子列表。排序并不重要,因此["a", 7][7, "a"]中的一个就足够了。

有任何提示吗? (也许是itertools的东西吗?)

3 个答案:

答案 0 :(得分:3)

这是一种方法:组合2个列表。然后做组合的结果。

from itertools import product, combinations, chain
res = list(chain.from_iterable(product(a, b) for a, b in combinations(lists, 2)))

print(res)
[('a', 7),
 ('a', 1),
 ('a', 2),
 ('a', 3),
 ('a', 5),
 ('b', 7),
 ('b', 1),
 ('b', 2),
 ('b', 3),
 ('b', 5),
 ('c', 7),
 ('c', 1),
 ('c', 2),
 ('c', 3),
 ('c', 5),
 ('a', 'alpha'),
 ('a', 'gamma'),
 ('b', 'alpha'),
 ('b', 'gamma'),
 ('c', 'alpha'),
 ('c', 'gamma'),
 (7, 'alpha'),
 (7, 'gamma'),
 (1, 'alpha'),
 (1, 'gamma'),
 (2, 'alpha'),
 (2, 'gamma'),
 (3, 'alpha'),
 (3, 'gamma'),
 (5, 'alpha'),
 (5, 'gamma')]

答案 1 :(得分:3)

itertools.combinations + itertools.productset理解为删除重复项

{item for z in (itertools.combinations(x, 2) for x in itertools.product(*lists)) for item in z}


{('a', 'alpha'),
 ('a', 'gamma'),
 ('a', 1),
 ('a', 2),
 ('a', 3),
 ('a', 5),
 ('a', 7),
 ('b', 'alpha'),
 ('b', 'gamma'),
 ('b', 1),
 ('b', 2),
 ('b', 3),
 ('b', 5),
 ('b', 7),
 ('c', 'alpha'),
 ('c', 'gamma'),
 ('c', 1),
 ('c', 2),
 ('c', 3),
 ('c', 5),
 ('c', 7),
 (1, 'alpha'),
 (1, 'gamma'),
 (2, 'alpha'),
 (2, 'gamma'),
 (3, 'alpha'),
 (3, 'gamma'),
 (5, 'alpha'),
 (5, 'gamma'),
 (7, 'alpha'),
 (7, 'gamma')}

答案 2 :(得分:1)

感谢@domochevksi的评论:

d.getClass.getDeclaredMethods.foreach(println)

# public int stringsimilarity.A$A55$A$A55$Decorator$$anon$2.x()
# private void stringsimilarity.A$A55$A$A55$Decorator$$anon$2.p()