Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination of lists from two lists of strings

I have two lists and I need to do a combination of strings from these lists, I have tried but I think it's not very efficient for larger 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 Output is:

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

Is there any more pythonic way to achieve it?

like image 881
Pradam Avatar asked Mar 15 '18 10:03

Pradam


2 Answers

A list comprehension is one way. "Pythonic" is subjective and I would not claim 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']]
like image 124
jpp Avatar answered Oct 23 '22 02:10

jpp


Possibly 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']]
like image 20
pylang Avatar answered Oct 23 '22 03:10

pylang