目前正在学习教程"Python的艰难之路“。
我正在学习列表和循环(ex32)。
在练习结束时,Zed (教程作者)告诉我们去玩,我已经这样做了。
# we can also build lists, first start with an empty one
elements = []
elements.append(range(0,6))
# then use the range function to do 0 to 5 counts
for element in elements:
print "Adding %s to elements" % element
# now we can print them out too
for element in elements:
print"Element was: %s" % element这产生的输出如下:
Adding [0, 1, 2, 3, 4, 5] to elements
Element was: [0, 1, 2, 3, 4, 5]我本以为会看到这样的事情:
Adding 0 to elements
Adding 1 to elements
Adding 2 to elements
Adding 3 to elements
Adding 4 to elements
Adding 5 to elements
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5但是Python想要在一个角色中打印出我的脚本,而不是与每个list组件连接的字符串。
我知道我可以更改脚本以准确地反映作者的脚本。
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was: %d" % i但我只想知道为什么我的作品不能像预期的那样工作?
发布于 2013-12-16 21:32:34
你是在把一个列表附加到一个列表中!你只想创建这个列表!
您所需要做的就是更改以下内容:
elements = []
elements.append(range(0,6))转到
elements = range(0,6)你就会得到你的预期结果
为什么
当您第一次创建elements时,它是一个空白列表。然后将range(0,6)附加到空列表中。现在元素看起来像[[0,1,2,3,4,5]] (或[range(0,6)]),它是一个有一个元素的列表,一个列表。
发布于 2013-12-16 21:32:58
这是因为elements恰好包含一个element,即list:[0, 1, 2, 3, 4, 5]。list.append()将项添加到列表的末尾。
In [1]: elements = []
In [2]: elements.append(range(0,6))
In [3]: elements
Out[3]: [[0, 1, 2, 3, 4, 5]]也许您是想http://docs.python.org/2/library/stdtypes.html#index-29列表:
In [1]: elements = []
In [2]: elements.extend(range(0, 6))
In [3]: elements
Out[3]: [0, 1, 2, 3, 4, 5]或者换掉它?
In [4]: elements = range(0,6)
In [5]: elements
Out[5]: [0, 1, 2, 3, 4, 5]甚至:
In [6]: elements = [element for element in range(0,6)]
In [7]: elements
Out[7]: [0, 1, 2, 3, 4, 5]在本例中,列表理解是不必要的,但它演示了如何容易地过滤或映射这些元素。
发布于 2013-12-16 21:33:30
.append向列表中添加一个元素。唯一的一个元素是range(0, 6),它是[0, 1, 2, 3, 4, 5] (Johnsyweb在我之前就把它引入了)。您可以使用.extend来追加每一个。
https://stackoverflow.com/questions/20621296
复制相似问题