1

我正在尝试在 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

但我知道我显然做错了至少几件事。任何帮助将不胜感激!

4

2 回答 2

4

怎么样:

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

或者可以说更具可读性:

map(''.join, zip(list1, list2))
于 2012-06-07T03:07:09.337 回答
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)
于 2012-06-07T03:11:40.050 回答