Python 从元组创建组合
我从数据库中获取数据。从数据库中,它们以元组的形式出现:Python 从元组创建组合,python,python-3.x,combinations,Python,Python 3.x,Combinations,我从数据库中获取数据。从数据库中,它们以元组的形式出现: [('test1', 'test12', 'test13', 'test14'), ('test21', 'test22', 'test23', 'test24'), ('test31', 'test32', 'test33', 'test34'), ('test41', 'test42', 'test43', 'test44'), ('test51', 'test52', 'test53', 'test54'), ('test6
[('test1', 'test12', 'test13', 'test14'),
('test21', 'test22', 'test23', 'test24'),
('test31', 'test32', 'test33', 'test34'),
('test41', 'test42', 'test43', 'test44'),
('test51', 'test52', 'test53', 'test54'),
('test61', 'test62', 'test63', 'test64'),
('test71', 'test72', 'test73', 'test74'),
('test81', 'test82', 'test83', 'test84'),
('test91', 'test92', 'test93', 'test94'),
('test11', 'test12', 'test13', 'test14')]
这就是我想要的:
将这些输入进行组合。。。所以我的输出有4个参数的组合(比如在示例中)和
1)最重要的是,新组合中的值始终处于其位置,即,如果原始组合中的值为索引[1],这意味着在新组合中,它也应为[1]
2)没有重复的组合
例如:
我得到了元组:
[('test91', 'test92', 'test93', 'test94'),
('test11', 'test12', 'test13', 'test14')]
从中我得到了新的组合:
[('test91', 'test12', 'test13', 'test14'),
('test11', 'test92', 'test93', 'test94')]
也许可以使用两两或其他方法。
帮助。您需要使用内置包中的方法,该方法提供输入项的笛卡尔乘积
下面是您想要的代码。
但是要小心,因为庞大的列表会产生大量的组合,所以尽量不要耗尽内存
from itertools import product
data = [('test91', 'test92', 'test93', 'test94'),
('test11', 'test12', 'test13', 'test14')]
b = list(zip(*a)) # making list of n-th elements
# b = [('test91', 'test11'), <- first elements
# ('test92', 'test12'), <- second elements
# ('test93', 'test13'), <- third elements
# ('test94', 'test14')]
variations = product(*b)
output = set(variations) - set(a) # this is unique variations without input data
# output = {('test11', 'test12', 'test13', 'test94'),
# ('test11', 'test12', 'test93', 'test14'),
# ('test11', 'test12', 'test93', 'test94'),
# ('test11', 'test92', 'test13', 'test14'),
# ('test11', 'test92', 'test13', 'test94'),
# ('test11', 'test92', 'test93', 'test14'),
# ('test11', 'test92', 'test93', 'test94'),
# ('test91', 'test12', 'test13', 'test14'),
# ('test91', 'test12', 'test13', 'test94'),
# ('test91', 'test12', 'test93', 'test14'),
# ('test91', 'test12', 'test93', 'test94'),
# ('test91', 'test92', 'test13', 'test14'),
# ('test91', 'test92', 'test13', 'test94'),
# ('test91', 'test92', 'test93', 'test14')}
如果你需要一个列表而不是集合,就这么做吧
output = list(output)
所以你想要所有元组的组合,那将是很多。是的,有很多可能的组合。蛮力方法:使用四个嵌套循环来捕获所有可能的组合。有n^4种可能的组合(n是4元组数组的行数),即使使用递归,我们也可以这样做。这是一个简单的方法。@jrook但是它是如何实现的。。。。
output = list(output)