使用基于 Python 索引的多列表添加列表元素

pythonserver side programmingprogramming更新于 2025/7/3 15:08:17

列表可以嵌套。这意味着我们将较小的列表作为较大列表中的元素。在本文中,我们解决了将简单列表的元素添加到嵌套列表的元素的挑战。如果列表的长度不同,则较小列表的长度将成为结果列表的最大长度。

以下是实现此目的的各种方法。

使用 for 循环

在此方法中,我们获取较小列表的长度并循环遍历此列表的元素,将其添加到较大列表的元素中。在这里我们使用 append 函数将每个元素附加到结果列表中。

示例

simple_list = [25, 35, 45, 55, 65]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15],[5,6]]
result_list = []

for n in range(len(simple_list)):
   var = []
   for m in nested_list[n]:
      var.append(m + simple_list[n])
   result_list.append(var)
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :",result_list)

输出

运行上述代码得到以下结果 −

The first list : [25, 35, 45, 55, 65]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15], [5, 6]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]

使用 enumerate()

enumerate() 函数接受列表或元组等集合并将其作为枚举对象返回。在这种方法中,我们首先创建一个具有枚举函数的外部 for 循环,以获取嵌套列表的每个元素,然后通过内部 for 循环将它们添加到简单列表中的相应元素中。

示例

simple_list = [25, 35, 45, 55, 65,25]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15]]
result_list = []

# 使用 enumerate
result_list = [[val + simple_list[p] for val in q] for p, q in enumerate(nested_list)]
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :",result_list)

输出

运行上述代码得到以下结果 −

The first list : [25, 35, 45, 55, 65, 25]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]

使用 zip()

在此方法中,我们重复上述程序,但使用 zip () 而不是枚举。zip() 将两个列表作为其输入。

示例

simple_list = [25, 35, 45, 55, 65,25]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15]]
result_list = []

result_list = [[w + u for w in v ]for u, v in zip(simple_list, nested_list)]

print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :",result_list)

输出

运行上述代码得到以下结果 −

The first list : [25, 35, 45, 55, 65, 25]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]

相关文章


有用资源