senera
senera

Reputation: 85

concatenate corresponding elements from different list into one list

I know there is a bunch of similar answers here but I tried at least 10 of them and did not work in my case since it also involves splitting the list and adding string...so any help is appreciated!

Write a function 'conjunctions' which recevies a nested list 'word_list'. This list contains a number of sublists, each a list of words (i.e. strings), such as:

[["Tom", "Laurel", "Merkel"], ["Jerry","Hardy", "Macron"]]

Note that all the sublists have the same number of words in them. Your function must return a list of strings, where each element in a position is an "and" conjunction of all the elements in the same position in all the sublists. For example:

conjunctions([["Tom", "Laurel", "Merkel"],["Jerry","Hardy", "Macron"]])

should return

['Tom and Jerry', 'Laurel and Hardy', 'Merkel and Macron']

and

conjunctions([["one", "apples"],["two","oranges"],["three","bananas"]])

should return:

['one and two and three', 'apples and oranges and bananas']

I spent hours but all I can do is to change the order of the elements but I don't know how to further concatenate them:

def conjunctions(word_list):
    name = []
    for word in word_list:
        for length in range(len(word)):
            for n in range(len(word_list)):
                name.append(word_list[n][length])
        return name

this will only return me a list like this (using example two):

['one', 'two', 'three', 'apples', 'oranges', 'bananas']

Thank you in advance for your help!

Upvotes: 0

Views: 160

Answers (3)

Derek Eden
Derek Eden

Reputation: 4618

I tried this on both of your example lists and it works:

def conjunctions(l):
    tmp=[]
    for l2 in range(len(l[0])):
        tmp.append(' and '.join([l1[l2] for l1 in l]))
    return tmp

using zip seems simpler though

Upvotes: 0

jeremie
jeremie

Reputation: 1131

One way to do so is to use zip

names = [["Tom", "Laurel", "Merkel"], ["Jerry","Hardy", "Macron"]]
[' and '.join(e) for e in zip(*names)]

This will print:

['Tom and Jerry', 'Laurel and Hardy', 'Merkel and Macron']

Upvotes: 0

Paul Rooney
Paul Rooney

Reputation: 21609

You can use zip and join the strings putting ' and ' in between them.

>>> x = [["Tom", "Laurel", "Merkel"], ["Jerry","Hardy", "Macron"]]
>>> y = [["one", "apples"],["two","oranges"],["three","bananas"]]
>>> def conjunctions(L):
...     return [' and '.join(p) for p in zip(*L)]
... 
>>> conjunctions(x)
['Tom and Jerry', 'Laurel and Hardy', 'Merkel and Macron']
>>> conjunctions(y)
['one and two and three', 'apples and oranges and bananas']

Using zip with the asterisk, means that the list is converted to a set of arguments to the function (see this) e.g. zip(*[[1,2], [3,4]]) becomes zip([1,2], [3,4]). You can think of it as stripping the outermost list.

Upvotes: 2

Related Questions