Python 这些函数在此列表中的功能细分?
打算生成包含Python 这些函数在此列表中的功能细分?,python,list,func,Python,List,Func,打算生成包含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 = [&qu
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"]
我更改了评论以使其可读:
def组合列表(列表1、列表2):
new_list=list2#使用列表2的元素定义一个新列表
对于反向(范围(len(list1)))中的i:#取数字0,1,2,3,。。。反向排列(列表1)
new_list.append(list1[i])#在list1中添加具有相应索引的元素
返回新列表#返回新列表
顺便说一句,你可以这样做:
组合列表=lambda l1,l2:l2+l1[:-1]
线路明细:
for i in reversed(range(len(list1)))
假设list1=[1,2,3]
然后len(list1)=3
,范围将生成从0
到2
的数字
reversed
将顺序翻转为数字2
,1
,0
,
要从范围迭代器对象打印它们,
您需要对其进行迭代,这就是for循环的作用:
for i in reversed(range(len(list1))):
print(i)
结果:
2
1
0
reversed(range(len(list1))
是编写python代码的可怕方式。在循环内打印i
的值,您将了解它的作用。使用没有反转的相同代码,然后打印相同的代码。若要调试和理解代码,请打印值,您将得到它len()
返回列表的长度range()
返回一个参数为最大值的列表。reversed()
返回此列表的反向迭代器,是的,您猜到了,顺序相反。如果n=len(list1)
,我将遍历数字[(n-1)、(n-2),…0]
。这是因为reversed只在相反方向上迭代,即范围(n)将是[0,…n-1]
。