内容简介:示例:上面给出了一个简单的示例,就是通过一次带有索引for循环每次循环中将两个list中对应的元素插入新的list。
如何合并两个长度相等的list?
示例:
-
输入:
- list1: [1, 2, 3]
- list2: ['a', 'b', 'c']
-
输出:
- [1, 'a', 2, 'b', 3, 'c']
方案1: 遍历两个数组
def interleave_by_loop(list1, list2):
if len(list1) != len(list2):
raise ValueError("传入的list的长度需要相等")
new_list = []
for index, value in enumerate(list1):
new_list.append(value)
new_list.append(list2[index])
return new_list
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
if __name__ == "__main__":
print(interleave_by_loop(list1, list2))
# [1, 'a', 2, 'b', 3, 'c']
上面给出了一个简单的示例,就是通过一次带有索引for循环
每次循环中将两个list中对应的元素插入新的list。
上面的方法可能是个比较通用的做法,但是在 Python 中可以写的简洁一点
方案2
def interleave(list1, list2):
return [val for pair in zip(list1, list2) for val in pair]
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
if __name__ == "__main__":
print(interleave(list1, list2))
# [1, 'a', 2, 'b', 3, 'c']
这里,我们首先观察下代码,首先
- zip(list1, list2) 把两个列表合并成一个元组列表
- 然后我们通过for循环得到一个个元组
- 最后把元组解析成我们的列表
其实,我们还可以修改下我们的函数,使得我们的函数更加具有通用性
def interleave(*args):
return [val for pair in zip(*args) for val in pair]
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['github', 'google.com', 'so']
if __name__ == "__main__":
print(interleave(list1, list2, list3))
# [1, 'a', 'github', 2, 'b', 'google.com', 3, 'c', 'so']
这样我们的函数就可以接受任意多个列表了!
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Ruby Programming Language
David Flanagan、Yukihiro Matsumoto / O'Reilly Media, Inc. / 2008 / USD 39.99
Ruby has gained some attention through the popular Ruby on Rails web development framework, but the language alone is worthy of more consideration -- a lot more. This book offers a definition explanat......一起来看看 《The Ruby Programming Language》 这本书的介绍吧!