gpt4 book ai didi

单步执行两个列表并避免 idx 的 Pythonic 风格?

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:59 24 4
gpt4 key购买 nike

(在我开始之前,让我们假设这是一个面试问题,我的目的是避免仅仅调用 sorted。)

我有这段有效的 Python 代码:

def merge_sorted_lists(left, right):
leftlen = len(left)
rightlen = len(right)
leftidx = 0
rightidx = 0
newlist = []
while leftidx < leftlen or rightidx < rightlen:
if rightidx == rightlen or left[leftidx] <= right[rightidx]:
newlist.append(left[leftidx])
leftidx += 1
elif leftidx == leftlen or right[rightidx] < left[leftidx]:
newlist.append(right[rightidx])
rightidx += 1
return newlist

我是一名长期的 C++ 程序员,最近学习了足够多的 Python,知道这“闻起来”非常不符合 Pythonic 的习惯,因为 idx 的大量使用。当迭代器的推进需要这种微调控制时,是否有更优雅的方式来迭代两个列表?

最佳答案

呃,作为第一个猜测,我会先尝试使用生成器。我使用 yield 而不是构建列表,因为 a) 生成器可以是无限的,并且 b) 嘿,一旦你开始使用生成器,不妨一直使用生成器。

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
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]

关于单步执行两个列表并避免 idx 的 Pythonic 风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com