首页 > 解决方案 > 这些功能在此列表中的作用的细分?

问题描述

一个基本程序,旨在生成一个包含 的元素的新列表list2。后面是逆序的元素,list1我似乎无法理解注释行的含义。

 def combine_lists(list1, list2):
      new_list = list2
      for i in reversed(range(len(list1))):   #this one
        new_list.append(list1[i])
      return new_list
    
    Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
    Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

标签: pythonlistfunc

解决方案


我更改了注释以使它们可读:

def combie_lists(list1, list2):
      new_list = list2  #define a new list with the elements of list 2
      for i in reversed(range(len(list1))): #takes the numbers 0,1,2,3,... to len(list1) in reverse
        new_list.append(list1[i]) #add the element in list1 with the corresponding index
      return new_list #return the new list

顺便说一句,你可以这样做:

combie_lists= lambda l1, l2: l2 + l1[::-1]

推荐阅读