进行组合
Making combinations
我是 Python 的初学者,我需要帮助来完成这项任务:
我有一个包含未知字符数的列表,其格式如下:
my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]
t
代表测试,v
代表测试的版本。我想获得测试之间所有可能的组合。在这种情况下,我将有 2x3=6 个测试组合。
combinations = ["t1v1_t2v1", "t1v1_t2v2", "t1v1_t2v3", "t1v2_t2v1", "t1v2_t2v2", "t1v2_t2v3"]
我无法在测试中进行组合,例如 "t1v1_t1v2"
是不可能的。而且,我可以有更多的测试,而不是这个例子中的两个。
请问我该怎么做?
您可以为此使用 itertools.products
,这应该适用于任意数量的测试 -
from itertools import product, groupby
tests = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3", "t3v1", "t3v2"]
# group the lists into lists of lists containing items of single test
lists = [list(l) for _, l in groupby(tests, lambda x: x[:2])]
output = list('_'.join(x) for x in product(*lists))
这里output
是-
['t1v1_t2v1_t3v1', 't1v1_t2v1_t3v2', 't1v1_t2v2_t3v1', 't1v1_t2v2_t3v2', 't1v1_t2v3_t3v1', 't1v1_t2v3_t3v2', 't1v2_t2v1_t3v1', 't1v2_t2v1_t3v2', 't1v2_t2v2_t3v1', 't1v2_t2v2_t3v2', 't1v2_t2v3_t3v1', 't1v2_t2v3_t3v2']
首先,我会根据测试编号将测试列表数据分成不同的组,然后我会生成每个测试编号的所有不同列表。两者都将使用来自 itertools
的 groupby
和 product
函数来实现
from itertools import groupby, product
def get_test_number(test_string):
return test_string[0:2]
my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]
groupby_result = groupby(my_list, get_test_number)
separated_tests = [list(v) for _, v in groupby_result]
products = product(*separated_tests)
strings_of_products = list(map("_".join, products))
print(strings_of_products)
我是 Python 的初学者,我需要帮助来完成这项任务:
我有一个包含未知字符数的列表,其格式如下:
my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]
t
代表测试,v
代表测试的版本。我想获得测试之间所有可能的组合。在这种情况下,我将有 2x3=6 个测试组合。
combinations = ["t1v1_t2v1", "t1v1_t2v2", "t1v1_t2v3", "t1v2_t2v1", "t1v2_t2v2", "t1v2_t2v3"]
我无法在测试中进行组合,例如 "t1v1_t1v2"
是不可能的。而且,我可以有更多的测试,而不是这个例子中的两个。
请问我该怎么做?
您可以为此使用 itertools.products
,这应该适用于任意数量的测试 -
from itertools import product, groupby
tests = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3", "t3v1", "t3v2"]
# group the lists into lists of lists containing items of single test
lists = [list(l) for _, l in groupby(tests, lambda x: x[:2])]
output = list('_'.join(x) for x in product(*lists))
这里output
是-
['t1v1_t2v1_t3v1', 't1v1_t2v1_t3v2', 't1v1_t2v2_t3v1', 't1v1_t2v2_t3v2', 't1v1_t2v3_t3v1', 't1v1_t2v3_t3v2', 't1v2_t2v1_t3v1', 't1v2_t2v1_t3v2', 't1v2_t2v2_t3v1', 't1v2_t2v2_t3v2', 't1v2_t2v3_t3v1', 't1v2_t2v3_t3v2']
首先,我会根据测试编号将测试列表数据分成不同的组,然后我会生成每个测试编号的所有不同列表。两者都将使用来自 itertools
groupby
和 product
函数来实现
from itertools import groupby, product
def get_test_number(test_string):
return test_string[0:2]
my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]
groupby_result = groupby(my_list, get_test_number)
separated_tests = [list(v) for _, v in groupby_result]
products = product(*separated_tests)
strings_of_products = list(map("_".join, products))
print(strings_of_products)