for 循环中的列表如何在 Python 中工作?
How does a list in a for loop work in Python?
所以我有这个代码:
def function(b):
a = []
for i in range(0,len(b),2)
a.append(b[i])
return a
def main():
a = [0,1,2,3,4,5,6,7,8,9,10,11]
for i in[51,"a", 3.2]
a = function(a)
print a
main()
我不明白 for 循环如何与列表 [51, "a", 3.2]
一起工作,以及为什么对于该列表它打印 [0, 8]
,但对于列表 [51, "a"]
打印 [0,4,8]
.
基本上每次您调用该函数时,它都会 return 您只有元素构成偶数索引。
然后你将它们存储回 a
所以每次你调用函数并存储结果时,你将列表减半,只存储偶数索引中的那些。列表 [52, "a", 3.2] 中的值基本上只是告诉调用函数的次数。
当你调用它 3 次时,你得到的结果会比调用它 2 次时少。如果你把打印放在循环中你可以看到这个
def function(b):
a = []
for i in range(0,len(b),2):
a.append(b[i])
return a
def main():
a = [0,1,2,3,4,5,6,7,8,9,10,11]
for i in[51,"a", 3.2]:
a = function(a)
print(a)
main()
输出
[0, 2, 4, 6, 8, 10]
[0, 4, 8]
[0, 8]
所以我有这个代码:
def function(b):
a = []
for i in range(0,len(b),2)
a.append(b[i])
return a
def main():
a = [0,1,2,3,4,5,6,7,8,9,10,11]
for i in[51,"a", 3.2]
a = function(a)
print a
main()
我不明白 for 循环如何与列表 [51, "a", 3.2]
一起工作,以及为什么对于该列表它打印 [0, 8]
,但对于列表 [51, "a"]
打印 [0,4,8]
.
基本上每次您调用该函数时,它都会 return 您只有元素构成偶数索引。
然后你将它们存储回 a
所以每次你调用函数并存储结果时,你将列表减半,只存储偶数索引中的那些。列表 [52, "a", 3.2] 中的值基本上只是告诉调用函数的次数。
当你调用它 3 次时,你得到的结果会比调用它 2 次时少。如果你把打印放在循环中你可以看到这个
def function(b):
a = []
for i in range(0,len(b),2):
a.append(b[i])
return a
def main():
a = [0,1,2,3,4,5,6,7,8,9,10,11]
for i in[51,"a", 3.2]:
a = function(a)
print(a)
main()
输出
[0, 2, 4, 6, 8, 10]
[0, 4, 8]
[0, 8]