我遇到了以下问题。
是否有快速python内置方法来执行以下操作:
Input: sets {1,2}, {3,4}, {6,7,8}
Output: sets {1,3,6}, {1,3,7}, {1,3,8}, {1,4,6}, {1,4,7}, {1,4,8}, {2,3,6}, {2,3,7}, {2,3,8}, {2,4,6}, {2,4,7}, {2,4,8}
谢谢!
答案 0 :(得分:2)
这是一种方法:
>>> map(set, itertools.product({1,2}, {3,4}, {6,7,8}))
[set([8, 1, 3]), set([1, 3, 6]), set([1, 3, 7]), set([8, 1, 4]), set([1, 4, 6]), set([1, 4, 7]), set([8, 2, 3]), set([2, 3, 6]), set([2, 3, 7]), set([8, 2, 4]), set([2, 4, 6]), set([2, 4, 7])]
请注意,集合是无序的。如果您需要保留排序,请使用列表或元组:
>>> map(tuple, itertools.product((1,2), (3,4), (6,7,8)))
[(1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 4, 6), (1, 4, 7), (1, 4, 8), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8)]
这很容易推广到可变数量的集合或其他集合:
>>> coll = ((1,2), (3,4), (6,7,8))
>>> map(tuple, itertools.product(*coll))
[(1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 4, 6), (1, 4, 7), (1, 4, 8), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8)]
答案 1 :(得分:1)
a = set([1,2])
b = set([3,4])
c = set([6,7,8])
print [set([x, y, z]) for x in a for y in b for z in c]
#[set([8, 1, 3]), set([1, 3, 6]), set([1, 3, 7]), set([8, 1, 4]), set([1, 4, 6]), set([1, 4, 7]), set([8, 2, 3]), set([2, 3, 6]), set([2, 3, 7]), set([8, 2, 4]), set([2, 4, 6]), set([2, 4, 7])]
答案 2 :(得分:1)
>>> from itertools import product
>>> list(product([1,2],[3,4,5],[6,7,8]))
[(1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 5, 6), (1, 5, 7), (1, 5, 8), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 5, 6), (2, 5, 7), (2, 5, 8)]