And*_*dei 0 python algorithm loops list
我有几个排序列表。如何高效、优雅地按排序顺序循环所有元素?在我的现实生活问题中,这些列表包含可直接比较和可排序的元素,但不同且需要不同的处理。
我更喜欢保留我的列表,这就是我手动复制它们的原因。如果像库函数这样的单行解决方案缺少这一点,我会很乐意使用它并事先复制列表。
这段代码实现了我想要的功能,但既不高效也不优雅。
from random import randint
a: list = []
b: list = []
c: list = []
list_of_lists: list = [a, b, c]
for i in range(10):
l = randint(0, 2)
list_of_lists[l].append(i)
print(a, b, c)
a_copy = a.copy()
b_copy = b.copy()
c_copy = c.copy()
# print the elements of the lists in sorted order
x = a_copy.pop(0)
y = b_copy.pop(0)
z = c_copy.pop(0)
while (x and x is not 1000) or \
(y and y is not 1000) or \
(z and z is not 1000):
if x is not 1000 and x < y and x < z:
print(x)
if a_copy and a_copy[0]:
x=a_copy.pop(0)
else:
x = 1000
elif y is not 1000 and y < x and y < z:
print(y)
if b_copy and b_copy[0]:
y=b_copy.pop(0)
else:
y = 1000
elif z is not 1000 and z < x and z < y:
print(z)
if c_copy and c_copy[0]:
z=c_copy.pop(0)
else:
z = 1000
Run Code Online (Sandbox Code Playgroud)
该heapq模块提供了将排序的可迭代对象合并到单个排序的迭代器中的函数。
from heapq import merge
merged = list(merge(a, b, c))
Run Code Online (Sandbox Code Playgroud)
例如,
>>> a, b, c
([1, 4, 7], [2, 5, 8], [3, 6, 9])
>>> from heapq import merge
>>> list(merge(a, b, c))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> (a, b, c)
([1, 4, 7], [2, 5, 8], [3, 6, 9])
Run Code Online (Sandbox Code Playgroud)