Reputation: 173
I had a similar question here but it's a different issue. I have two lists. list0 is a list of strings and list1 is a list of lists consisting of ints.
# In this example are 8 strings
list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
list1 = [ [0, 1], [2], [3], [4,5,6], [7] ...... ]
# therefore 8 ints, 0 - 7; it always starts with 0.
There are exact the same number of strings in list0
as ints in list1
.
I want to loop through the items of list1 ([0,1], [2], ...
) and concatenate the strings from list0 according to the int numbers of the item from list1
. So new_list[0]+new_list[1]
should beconcatenated, 2 and 3 not, than 4+5+6 should be concatenated and so on... I don't know how to do that in one single for loop since the amount of ints in one item can vary. So what I am looking for is a new concatenated list that should look like this:
# 0 and 1 2 3 4 5 6 7
new_list = ["TestTest", "More text", "Test123", "tttabcokokok", "Hello"]
How can I do this?
Upvotes: 3
Views: 106
Reputation: 142206
I'd go for operator.itemgetter
and a list-comp*, eg:
from operator import itemgetter
list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
list1 = [ [0, 1], [2], [3], [4,5,6], [7] ]
new = [''.join(itemgetter(*indices)(list0)) for indices in list1]
# ['TestTest2', 'More text', 'Test123', 'tttabcokokok', 'Hello']
* Well - no I'd go for the list-comp - it's faster and doesn't require an import... Consider this an alternative though...
Upvotes: 4
Reputation: 1123520
Use list comprehensions and str.join()
:
new_list = [''.join([list0[i] for i in indices]) for indices in list1]
Demo:
>>> list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
>>> list1 = [ [0, 1], [2], [3], [4,5,6], [7]]
>>> [''.join([list0[i] for i in indices]) for indices in list1]
['TestTest2', 'More text', 'Test123', 'tttabcokokok', 'Hello']
Upvotes: 9