本文介绍了使用两个先前列表中的值创建新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定长度相同的列表list1和list2,创建一个新列表,该列表由list1的最后一个元素,list2的最后一个元素,list1的第二个到最后一个元素,第二个list2的最后一个元素,以此类推(换句话说,新列表应该由list1和list2的相反元素交替组成).例如,如果list1包含[1,2,3]和list2包含[4,5,6],则新列表应包含[3,6,2,5,5,1,4].将新列表与变量list3关联.

Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2 , followed by the second to last element of list1 , followed by the second to last element of list2 , and so on (in other words the new list should consist of alternating elements of the reverse of list1 and list2 ). For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6] , then the new list should contain [3, 6, 2, 5, 1, 4] . Associate the new list with the variable list3 .

我的代码:

def new(list1,list2):
    i = 0
    j = 0
    new_list = []
    for j in list1:
        new_list[i-1] = list2[j-1]
        i+= 1
        j += 1
        new_list[i-1] = list2 [j-1]
        i+= 1
        j += 1
    return new_list

我知道,这很麻烦= _ =,有帮助吗?

I know, it's messy =_=, help?

推荐答案

l1 = [1,2,3]
l2 = [4,5,6]

newl = []
for item1, item2 in zip(reversed(l1), reversed(l2)):
    newl.append(item1)
    newl.append(item2)

print newl

这篇关于使用两个先前列表中的值创建新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 02:52