带有两个迭代器的python一次递增1
作者:互联网
我是python的新手.
我尝试在python中实现诸如归类排序之类的操作.我使用https://pythonhosted.org/llist/#sllist-objects的单链列表.要合并两个排序的列表,我需要使用迭代器遍历两个列表.伪代码如下所示:
n3 = sllist()
for n1 in list1 and n2 in list2:
if (n1 > n2):
n3.append(n1)
n1++ # c way of doing thing
else:
n3.append(n2)
n2++ # c way of doing thing
但是我不知道如何使它在python中工作.任何指针或提示都会有所帮助.
编辑:
在所有讨论和建议之后,我想到了类似这样的代码.谁能告诉我,如何摆脱最后两个while循环.我打算使用“扩展”,但无法使用它.
final_list = sllist()
node1 = list1.first
node2 = list2.first
while node1 and node2:
if node1.value < node2.value:
final_list.append(node1)
node1 = node1.next
else:
final_list.append(node2)
node2 = node2.next
while node1:
final_list.append(node1)
node1 = node1.next
while node2:
final_list.append(node2)
node2 = node2.next
return final_list
解决方法:
我通常使用iterables和next执行此操作:
lst1 = iter(list1)
lst2 = iter(list2)
out = sllist()
sentinel = object()
n1 = next(lst1, sentinel)
n2 = next(lst2, sentinel)
while n1 is not sentinel and n2 is not sentinel:
if n1 > n2:
out.append(n2)
n2 = next(lst2, sentinel)
elif n2 >= n1:
out.append(n1)
n1 = next(lst1, sentinel)
out.extend(lst1)
out.extend(lst2)
正如评论中指出的那样,您还可以将其编写为:
lst1 = iter(list1)
lst2 = iter(list2)
out = sllist()
try:
n1 = next(lst1)
n2 = next(lst2)
while True:
if n1 > n2:
out.append(n2)
n2 = next(lst2)
elif n2 >= n1:
out.append(n1)
n1 = next(lst1)
except StopIteration: # raised when next(...) fails.
out.extend(lst1)
out.extend(lst2)
它在功能上是等效的.选择您喜欢的任何一个:-)
标签:mergesort,iterator,linked-list,python 来源: https://codeday.me/bug/20191029/1958319.html