【发布时间】:2020-11-29 12:11:26
【问题描述】:
我知道有一个非常相似的问题:Itertools product without repeating duplicates
但我有一些不同的东西。例如:
a = ['add', 'sub']
b = [2,3, 'a', 'b']
c = [1,3, 'a', 'c']
list(it.product(a, b, c)) # result is:[('add', 2, 1),('add', 2, 3),('add', 2, 'a'), ('add', 2, 'c'),
#('add', 3, 1),('add', 3, 3),('add', 3, 'a'),('add', 3, 'c'),('add', 'a', 1),('add', 'a', 3),
#('add', 'a', 'a'),('add', 'a', 'c'), ('add', 'b', 1),('add', 'b', 3),('add', 'b', 'a'),
#('add', 'b', 'c'),('sub', 2, 1),('sub', 2, 3),('sub', 2, 'a'),('sub', 2, 'c'),('sub', 3, 1),
#('sub', 3, 3),('sub', 3, 'a'),('sub', 3, 'c'),('sub', 'a', 1),('sub', 'a', 3),('sub', 'a', 'a'),
#('sub', 'a', 'c'),('sub', 'b', 1),('sub', 'b', 3),('sub', 'b', 'a'),('sub', 'b', 'c')]
结果:
我不想将add(a,a) 作为第一个值 == 第二个值。
我只想保留add(3,a)、add(a,3) 中的 1 个,因为它是对称的。
我的示例只包含两个列表,但我可能会使用 5 个或更多列表来生成产品。
我不能使用combinations,因为:
product(['add', 'sub', 1,2,3, 'a','b', 'c'], repeat=3) 与 product(['add', 'sub'], [2,3, 'a', 'b'], [1,3, 'a', 'c']) 不同
product(['add', 'sub', 1,2,3, 'a','b', 'c'], repeat=3) 中的某些内容不适合我。
我想要一个快速的方法,因为我的程序是时间敏感的。
【问题讨论】:
-
add(3,a)和add(a,3)是对称的,但对于'sub'是否同样适用(假设这些是已知函数)? -
@Tomerikoo 是的,我认为它们相同,我正在尝试自动生成有意义的 expr。 sub(a, 2) 和 sub(2, a) 对我来说是一样的。因为它没有提供额外的含义。并感谢您编辑问题,我的语法不好
-
你能有
('add', 'c', 2)吗?
标签: python combinations product itertools