Reputation: 11
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
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
Reputation: 98816
How about:
map(lambda x: ''.join(x), zip(list1, list2))
Or arguably more readable:
map(''.join, zip(list1, list2))
Upvotes: 4