在 Python 中合并多个列表

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,我们可以使用各种方法将两个或多个列表合并为一个列表。其中一种方法是根据输入列表中元素的位置将它们组合起来。在这个挑战中,你将负责编写一个函数,将多个列表合并为一个列表的列表。

合并列表

编写一个名为 merge(*args, fill_value=None) 的函数,它接受两个或更多列表作为参数,并返回一个列表的列表。该函数应根据输入列表中元素的位置将它们组合起来。如果某个列表比最长的列表短,函数应用 fill_value 填充剩余的元素。如果未提供 fill_value,则应默认为 None

你的任务是实现 merge() 函数。

def merge(*args, fill_value = None):
  max_length = max([len(lst) for lst in args])
  result = []
  for i in range(max_length):
    result.append([
      args[k][i] if i < len(args[k]) else fill_value for k in range(len(args))
    ])
  return result
merge(['a', 'b'], [1, 2], [True, False]) ## [['a', 1, True], ['b', 2, False]]
merge(['a'], [1, 2], [True, False]) ## [['a', 1, True], [None, 2, False]]
merge(['a'], [1, 2], [True, False], fill_value = '_')
## [['a', 1, True], ['_', 2, False]]

总结

在这个挑战中,你学习了如何在 Python 中将两个或多个列表合并为一个列表的列表。你还学习了如何使用 max() 函数、列表推导式和 range() 函数来解决这个问题。记住使用 fill_value 参数来填充较短列表中的缺失值。