[英]For-loop only returns last value
I am trying this code on python:我正在 python 上尝试此代码:
N = 5
for n in xrange (0, N):
a = [10 + n]
print(a[0])
The code returns 14
, and when I try to print(a[1])
I have a list index error.代码返回
14
,当我尝试print(a[1])
时出现列表索引错误。 What I want is to be able to view a[0]
, a[1]
... a[n]
.我想要的是能够查看
a[0]
, a[1]
... a[n]
。 When I write a=[10 + n for n in xrange (0,N)]
it works but I don't understand the difference.当我写
a=[10 + n for n in xrange (0,N)]
时,它可以工作,但我不明白其中的区别。 Can anyone help on how to make the first method work?任何人都可以帮助如何使第一种方法起作用吗?
You aren't appending to a list;您没有附加到列表中; you are repeatedly redefining which single-element list
a
refers to.您反复重新定义
a
所指的单元素列表。
a = []
for n in range(N):
a.append(10 + n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.