1

I am a beginner in Python and I need a help with this task:

I have a a list with unknown number of characters that have a following form:


my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]

t stands for a test and v stands for a version of the test. I would like to get all possible combinations between tests. In this case I will have 2x3=6 combinations of tests.

combinations = ["t1v1_t2v1", "t1v1_t2v2", "t1v1_t2v3", "t1v2_t2v1", "t1v2_t2v2", "t1v2_t2v3"]

I cannot make combinations within a test, for example "t1v1_t1v2"is not possible. Moreover, I can have more tests, not just two as in this example.

How can I do this, please?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
vojtam
  • 1,157
  • 9
  • 34
  • If you have three tests would you want to include combinations of three? e.g. `t1v1_t2v1_t3v2`? Or just all of the pairings like `t1v1_t2v1`, `t1v1_t3v2` etc.? – Stuart Feb 08 '22 at 14:46
  • @Stuart the first one, so `t1v1_t2v1_t3v2`. thanks! – vojtam Feb 08 '22 at 14:47
  • These are **not combinations**. You want to group the inputs by test number, and then perform a Cartesian product. – Karl Knechtel Jun 25 '22 at 03:05

2 Answers2

2

You can use itertools.product for this. The following code should work for any number of tests:

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))

here output is -

['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']
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Max
  • 668
  • 4
  • 13
  • 1
    This works, thanks! Separated lists can be done using groupby_result = groupby(my_list, lambda v: v[0:2]) lists = [list(v) for _, v in groupby_result] – vojtam Feb 08 '22 at 15:01
2

First, I would separate the test list data into different groups based on their test number, then I would product all the different lists of each test number. Both will be achieved using groupby and product function from itertools

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)
Bao Huynh Lam
  • 974
  • 4
  • 12