python - 返回列表,其中元素从轮流/python中的列表中获取
问题描述
我需要帮助将 2 个列表转换为轮流从两个列表中获取元素的位置
def combine_lists(a, b):
"""
combine_lists([1, 2, 3], [4]) => [1, 4, 2, 3]
combine_lists([1], [4, 5, 6]) => [1, 4, 5, 6]
combine_lists([], [4, 5, 6]) => [4, 5, 6]
combine_lists([1, 2], [4, 5, 6]) => [1, 4, 2, 5, 6]
:param a: First list
:param b: Second list
:return: Combined list
"""
我尝试了什么:
# return a[0], b[0], a[1], b[1]
combined_list = []
for x, y in range (len(a), len(b)):
combined_list = a[x], b[y]
return combined_list
解决方案
看起来你想要itertools.zip_longest
:
from itertools import zip_longest
def combine_lists(*l):
return [j for i in zip_longest(*l) for j in i if j]
combine_lists([1, 2], [4, 5, 6])
# [1, 4, 2, 5, 6]
combine_lists([1, 2, 3], [4])
# [1, 4, 2, 3]
combine_lists([], [4, 5, 6])
# [4, 5, 6]
推荐阅读
- amazon-web-services - 如何从 Dynamodb 表中扫描带有冒号“:”的值?
- r - 将日期标签从奇数年更改为偶数年
- php - 消息信息 WooCommerce
- mysql - 如何根据 SQL 中另一个表的值将值插入表中?
- python - 如何在 Daml-dazl app 上通过密钥查找交易?
- reactive - 如何在 SparkAR 中不断添加数字(+= 等效项)
- c# - 有没有办法在实现类中调用默认接口方法?
- python - 使用 Pythons argparse 使参数成为标志或接受参数
- c# - BinaryFormatter 似乎弄乱了嵌套字典
- php - 使用 PHP 存储 PostgreSQL OID 图像