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


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

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

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

示例

 在线演示

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

# using 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()代替enumerate。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]]

更新于:2020年2月18日

519 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.