首页 > 解决方案 > 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!

标签: pythonpython-3.x

解决方案


您还可以使用列表推导:

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 中的约定是仅对类使用大写名称)


推荐阅读