我有几个排序列表。如何高效、优雅地按排序顺序循环所有元素?在我的现实生活问题中,这些列表包含可直接比较和可排序的元素,但不同且需要不同的处理。
我更喜欢保留我的列表,这就是我手动复制它们的原因。如果像库函数这样的单行解决方案缺少这一点,我会很乐意使用它并事先复制列表。
这段代码实现了我想要的功能,但既不高效也不优雅。
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) …Run Code Online (Sandbox Code Playgroud)