3

I have 2 list of lists:

a = [['Apple'], ['Banana']]
b = [[1,2,3,4], [4,5,6]]

How can I concatenate as strings element wise and get a new list of lists as below:

new_list = [['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

Best Regards.

4 Answers 4

4

Using itertools.cycle

Ex:

from itertools import cycle

a = [['Apple'], ['Banana']] 
b = [[1,2,3,4], [4,5,6]]

result = [[m+str(n) for m, n in zip(cycle(i), j) ] for i,j in zip(a, b)]
print(result)

Output:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]
Sign up to request clarification or add additional context in comments.

Comments

2

One without itertools:

[["%s%s" % (i[0], n) for n in j] for i,j in zip(a,b)]

Output:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

Comments

1

can this help you?

a = [['Apple'], ['Banana']]
b = [[1,2,3,4], [4,5,6]]
print([
    [c + str(d) for d in j for c in i] for i, j in zip(a, b)
])

Output:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

Comments

1

you can use 2 for loops:

new_list = []
for [item], numbers in zip(a, b):
    item_list = []
    for n in numbers:
        item_list.append(f'{item}{n}')
    new_list.append(item_list)

new_list

output:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

or you can use list comprehension:

[[f'{item}{n}' for n in numbers] for [item], numbers in zip(a, b)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.