python - Taking every first, second, third elements from two lists
问题描述
I have two lists that I've created using import random, so their elements and lengths are random. My aim is to get every first, second, third, etc. from these lists. For example, these are my two list outputs.
My list length is 4
List1 (Original List): [62, 51, 66, 57]
List 2 (Sum of neighbors of List 1): [113, 179, 174, 123]
My aim is to get,
List3: [62, 113, 51, 179, 66, 174, 57, 123]
This is my only attempt but it is completely incorrect.
def order(list1, list2):
list3=[]
result_num = []
for i in range(len(list1)):
result_num.extend(list1[i::3])
return result_num
result = order(list1)
Is it possible to write this program without any third party library? Any help would be appreciated!
解决方案
您还可以使用列表推导:
list1 = [62, 51, 66, 57]
list2 = [113, 179, 174, 123]
list3 = [value for pair in zip(list1, list2) for value in pair]
print(list3)
# [62, 113, 51, 179, 66, 174, 57, 123]
(作为旁注,我从列表名称中删除了大写字母 - Python 中的约定是仅对类使用大写名称)
推荐阅读
- javascript - 两个给定时间戳Javascript剩余的时间百分比
- sql - SQL选择依赖于条件计数
- python-3.x - 第三次尝试时未出现授予的访问权限
- javascript - 如何根据条件将项目添加到数组
- java - 如何克隆循环链接列表
- c# - 从插入的记录中取回唯一标识符
- apache-spark - PySpark sql 数据框 pandas UDF - java.lang.IllegalArgumentException:要求失败:小数精度 8 超过最大精度 7
- c - 如何使用 C 识别 GNU/Linux 上的以太网适配器
- objective-c - NSPredicate 检查字符串属性中的任何单词是否与 Swift 中的搜索词匹配
- javascript - 同一 Handlebars 脚本中的不同事件