user1441171
user1441171

Reputation: 11

combining two lists in jython

I am trying to write a function in jython that will combine the elements from two different lists in order to create one word.

For example:

the function takes two lists both names as a and b

if a is ["eat", "pray", "love"] and b is ["er", "ing", "d"] and you typed in makeWord(a,b) it would return with:

["eater", "praying", "loved"]

so far I have:

def makeWords(a,b):
     a = []
    list1 = a
    b = []
    list2 = b
    new_list = []
    for word in list1:
        new_list.append((list1[i] + list2[i]))
    return new_list

but i know i am obviously doing at least a few things wrong. any help would greatly be appreciated!!

Upvotes: 1

Views: 1015

Answers (2)

Blender
Blender

Reputation: 298364

This should work as well:

>>> a = ["eat", "pray", "love"]
>>> b = ["er", "ing", "d"]
>>> [start + end for start, end in zip(a, b)]
['eater', 'praying', 'loved']

For Joel Cornett, the timeit code:

import timeit

a = '''
a = ["eat", "pray", "love"]
b = ["er", "ing", "d"]
[start + end for start, end in zip(a, b)]
'''

b = '''
a = ["eat", "pray", "love"]
b = ["er", "ing", "d"]
map(lambda x: ''.join(x), zip(a, b))
'''

c = '''
a = ["eat", "pray", "love"]
b = ["er", "ing", "d"]
map(''.join, zip(a, b))
'''

timeit.Timer(a).timeit(number=1000000)
timeit.Timer(b).timeit(number=1000000)
timeit.Timer(c).timeit(number=1000000)

Upvotes: 2

Cameron
Cameron

Reputation: 98816

How about:

map(lambda x: ''.join(x), zip(list1, list2))

Or arguably more readable:

map(''.join, zip(list1, list2))

Upvotes: 4

Related Questions