我正在尝试在jython中编写一个函数,它将组合来自两个不同列表的元素以创建一个单词。
例如:
该函数采用两个列表,两个名称分别为a和b
如果a是["eat", "pray", "love"]
而b是["er", "ing", "d"]
然后输入makeWord(a,b)
它将返回:
["eater", "praying", "loved"]
到目前为止,我有:
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
但我知道我显然至少做了一些错事。任何帮助将非常感谢!!
答案 0 :(得分:4)
怎么样:
map(lambda x: ''.join(x), zip(list1, list2))
或者说可读性更高:
map(''.join, zip(list1, list2))
答案 1 :(得分:2)
这也应该有效:
>>> a = ["eat", "pray", "love"]
>>> b = ["er", "ing", "d"]
>>> [start + end for start, end in zip(a, b)]
['eater', 'praying', 'loved']
对于Joel Cornett,timeit
代码:
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)