擅长:python、mysql、java
<p>呃,首先,我想先用发电机来代替。我使用yield而不是构建一个列表,因为a)生成器可以是无限的,b)嘿,一旦你开始使用生成器,不妨一直使用生成器。你知道吗</p>
<pre><code>def merge(left,right):
left = iter(left)
right = iter(right)
left_val = next(left)
right_val = next(right)
try:
while True:
if left_val <= right_val:
yield left_val
left_val = next(left) #left.next() in python2
else:
yield right_val
right_val = next(right)
except StopIteration: #I have exhausted one of the iterators
if left_val <= right_val:
#left list depleted
yield right_val
for i in right: yield i #or use yield from right, if your python is fancy enough
else:
#right list depleted
yield left_val
for i in left: yield i
</code></pre>
<pre><code>In [2]: f = merge([0,4,17],[2,4,5,6,6,6])
In [3]: list(f)
Out[3]: [0, 2, 4, 4, 5, 6, 6, 6, 17]
</code></pre>