这些与数据结构相关的代码行在做什么?

What are these data-structure-related lines of code doing?

我正在训练我所学的知识并重新做一些练习以使这些信息牢记在心。

我正在练习创建一个函数,它的目标是同时遍历 2 个列表,并将它们中的数据放入一个列表中,我需要 return 作为目标输出。现在,我已经完成了练习,只是无法理解末尾的 2 行是为了让我通过练习。我做其他一切都很好只是不明白这两行代码的必要性。希望能帮助我们理解这些词的含义,它们的作用,以及为什么它们在那里。

假设我们有一个示例 2 列表:

list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 6, 8, 9, 10]

def get_sorted_union(list1, list2):
  i, j = 0, 0
  list_to_return = []
  while i < len(list1) and j < len(list2):
    if list1[i] > list2[j]:
      list_to_return.append(list2[j])
      j += 1
    elif list1[i] < list2[j]:
      list_to_return.append(list1[i])
      i += 1
    else:
      list_to_return.append(list1[i])
      i += 1
      j += 1
  list_to_return += list1[i:] #Those are the 2 lines i cant understand why they exist. v
  list_to_return += list2[j:]
  return list_to_return

最后两行将输入列表的其余部分添加到输出中。

当您的输入列表长度不同时,这很重要。例如

list1 = [1,4,5]
list2 = [2]

现在,当代码到达这些行时,i = 1 和 j = 1。您的 list_to_return 只有 [1,2],但您想添加 list1 [4,5] 中的剩余元素] 也加入此列表

一旦您获取了其中一个列表的所有元素,另一个列表很可能仍将包含元素,并且由于您的 AND 子句,您的 while 循环将不再继续。 list_to_return += list1[i:]list1 中的任何剩余元素附加到 list_to_return[i:] 表示从索引 i 到列表末尾的所有元素。