Combination of lists of two line lists

I have two lists, and I need to make a combination of strings from these lists, I tried, but I think this is not very effective for large lists.

data = ['keywords', 'testcases'] data_combination = ['data', 'index'] final_list = [] for val in data: for comb in range(len(data_combination)): if comb == 1: final_list.append([val] + data_combination) else: final_list.append([val, data_combination[comb]]) 

My way out:

  [['keywords', 'data'], ['keywords', 'data', 'index'], ['testcases', 'data'], ['testcases', 'data', 'index']] 

Is there any other pythonic way to achieve it?

+5
source share
2 answers

Understanding the list is one way. "Pythonic" is subjective, and I would not argue that this is the most readable or desirable method.

 data = ['keywords', 'testcases'] data_combination = ['data', 'index'] res = [[i] + data_combination[0:j] for i in data \ for j in range(1, len(data_combination)+1)] # [['keywords', 'data'], # ['keywords', 'data', 'index'], # ['testcases', 'data'], # ['testcases', 'data', 'index']] 
+7
source

Perhaps even more Pythonic:

code

 data = ["keywords", "testcases"] data_combination = ["data", "index"] [[x] + data_combination[:i] for x in data for i, _ in enumerate(data_combination, 1)] 

Output

 [['keywords', 'data'], ['keywords', 'data', 'index'], ['testcases', 'data'], ['testcases', 'data', 'index']] 
+1
source

Source: https://habr.com/ru/post/1275904/


All Articles