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?
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']]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With