python - 如何生成没有重复和对称的 itertools 产品?
问题描述
我知道有一个非常相似的问题: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)
, 作为第一个值 == 第二个值。
我只想保留 , 中的 1 个add(3,a)
,add(a,3)
因为它是对称的。
我的示例只包含两个列表,但我可以使用 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)
不适合我。
我想要一个快速的方法,因为我的程序是时间敏感的。
解决方案
IIUC,你可以这样做:
from itertools import product, combinations, chain
a = ['add', 'sub']
b = [2, 3, 'a', 'b']
c = [1, 3, 'a', 'c']
for operation, operands in product(a, combinations(set(chain(b, c)), r=2)):
print((operation, *operands))
输出
('add', 1, 2)
('add', 1, 3)
('add', 1, 'a')
('add', 1, 'b')
('add', 1, 'c')
('add', 2, 3)
('add', 2, 'a')
('add', 2, 'b')
('add', 2, 'c')
('add', 3, 'a')
('add', 3, 'b')
('add', 3, 'c')
('add', 'a', 'b')
('add', 'a', 'c')
('add', 'b', 'c')
('sub', 1, 2)
('sub', 1, 3)
('sub', 1, 'a')
('sub', 1, 'b')
('sub', 1, 'c')
('sub', 2, 3)
('sub', 2, 'a')
('sub', 2, 'b')
('sub', 2, 'c')
('sub', 3, 'a')
('sub', 3, 'b')
('sub', 3, 'c')
('sub', 'a', 'b')
('sub', 'a', 'c')
('sub', 'b', 'c')
推荐阅读
- node.js - Docker 构建错误:- npm ERR!超出最大调用堆栈大小
- stripe-payments - 在 webhook 触发器中更改 Stripe 示例电子邮件
- c# - 从网络框架应用程序使用托管标识连接到 Azure 应用程序配置
- node.js - Nestjs/微服务不创建可观察对象?
- windows - 有没有办法使用 ou 规范名称将 GPO 与 ou 联系起来?
- java - 在没有安装tomcat的情况下在localhost上运行war文件
- git - 有没有办法在没有 gitignore 的情况下停止在 VS Code 中跟踪文件夹?
- json - 从 Kafka 解析嵌套 json 的模式
- git - Husky Hooks 上的附加命令失败
- python - 如何删除数据框中的换行符?