user3921266
user3921266

Reputation:

Concatenate list items

I need to do something which must be easy enough, but for some reason, I can't get my head around to it.

So, basically, I need to produce a new list that will concatenate the items from three lists with each other.

Please note that all the three lists are currently in a dictionary a.

For clarity, here's what I'm trying to do:

def test(phrase):
    a = {}
    tmp = phrase.split(' ')
    for m in xrange(0,len(tmp)):

        a[m] = anagrammes2(tmp[m])
        # The anagram function will spit out the anagrams of the words
        # a[1] = ['mange']
        # a[2] = ['ton, 'ont']
        # a[3] = ['orange','onagre','organe','rongea']

test('Mange ton orange')

#result should be:
['mange ont onagre', 'mange ont orange', 'mange ont orangé', 'mange ont organe', 
 'mange ont rongea', 'mange ton onagre', 'mange ton orange', 'mange ton orangé', 
 'mange ton organe', 'mange ton rongea', 'mangé ont onagre', 'mangé ont orange', 
 'mangé ont orangé', 'mangé ont organe', 'mangé ont rongea', 
 'mangé ton onagre', 'mangé ton orange', 'mangé ton orangé', 
 'mangé ton organe', 'mangé ton rongea']

Upvotes: 4

Views: 107

Answers (2)

Mike Müller
Mike Müller

Reputation: 85432

You can use itertools.product():

>>> a = [['mange'], ['ton', 'ont'], ['orange','onagre','organe','rongea']]
>>> from itertools import product
>>> [' '.join(x) for x in product(*a)]
['mange ton orange',
 'mange ton onagre',
 'mange ton organe',
 'mange ton rongea',
 'mange ont orange',
 'mange ont onagre',
 'mange ont organe',
 'mange ont rongea']

Integrate with your code:

def test(phrase):
    anas = [anagrammes2(word) for word in phrase.split(' ')]
    return [' '.join(x) for x in product(*anas)]

test('Mange ton orange')

Upvotes: 1

zondo
zondo

Reputation: 20336

Assuming they are strings:

result = tuple(listA[x % len(listA)] + listB[x % len(listB)] + listC[x % len(listC)] for x in range(max(len(listA), len(listB), len(listC))))

Upvotes: 0

Related Questions