Python如何用切片等无循环方法实现双列表奇偶索引元素组合?
无需显式for循环的实现方法
方法1:切片赋值(最直接)
这种方法利用Python的切片赋值特性,完全无需编写循环代码:
another_list = [1, 2, 3, 4, 5, 6] my_list = ['a', 'b', 'c', 'd', 'e', 'f'] # 初始化一个长度与原列表一致的占位列表 output_list = [None] * len(another_list) # 偶数索引位置(0,2,4...)批量赋值为another_list的对应元素 output_list[::2] = another_list[::2] # 奇数索引位置(1,3,5...)批量赋值为my_list的对应元素 output_list[1::2] = my_list[1::2] print(output_list) # 输出: [1, 'b', 3, 'd', 5, 'f']
原理:output_list[::2]会选中列表中所有偶数索引的位置,直接将another_list[::2](another_list的偶数索引元素)批量赋值过去;同理output_list[1::2]选中奇数索引位置,完成对应元素的批量赋值。
方法2:结合itertools.chain合并配对元素
如果不想初始化占位列表,可以结合切片和itertools.chain实现:
from itertools import chain another_list = [1, 2, 3, 4, 5, 6] my_list = ['a', 'b', 'c', 'd', 'e', 'f'] # 先提取两个列表的目标切片,配对后展开为连续列表 output_list = list(chain.from_iterable(zip(another_list[::2], my_list[1::2]))) print(output_list) # 输出: [1, 'b', 3, 'd', 5, 'f']
原理:another_list[::2]得到[1,3,5],my_list[1::2]得到['b','d','f'];zip将两个切片的元素一一配对成元组(1,'b'), (3,'d'), (5,'f');最后chain.from_iterable把这些元组展开成一个连续的列表。
注意:以上两种方法都要求another_list和my_list长度相同,否则会出现赋值不匹配的问题。
内容的提问来源于stack exchange,提问作者Chathur
相关产品推荐
相关产品推荐

