简体   繁体   English

python中的笛卡尔积,但不是对,而是集合

[英]Cartesian product in python, but instead of pairs, sets

How would I be able to find all the combinations between two sets of characters in python, kind of like a cartesian product, but I don't want there to be pairs but subsets of the combinations.我如何才能在 python 中找到两组字符之间的所有组合,有点像笛卡尔积,但我不希望有成对,而是组合的子集。

For example:例如:

Let's say we have two sets with three elements假设我们有两个包含三个元素的集合

a = {"a", "b", "c"}
b = {"a", "b", "c"}

How would I get this output:我将如何获得此输出:

c = {{"a", "a"}, {"a", "b"}, {"a", "c"}, {"b", "a"}, {"b", "b"}, {"b", "c"}, {"c", "a"}, {"c", "b"}, {"c", "c"}}

You will be unable to get the output you asked for because - for example {'a', 'a'} is not valid value (sets do not allow duplicates and this value would just be 'a').您将无法获得您要求的输出,因为 - 例如 {'a', 'a'} 不是有效值(集合不允许重复,该值仅为 'a')。

However you can achieve the result you are aiming for by creating a set of tuples as such:但是,您可以通过创建一组元组来实现您想要的结果:

set([(x, y) for x in a for y in b])

output: {('b', 'a'), ('a', 'a'), ('b', 'b'), ('a', 'b'), ('c', 'b'), 
         ('c', 'c'), ('b', 'c'), ('a', 'c'), ('c', 'a')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM