为什么命令append(i)添加上一次调用的最后一个元素?

时间:2018-07-16 09:45:24

标签: python python-2.7 append

我正在做Shaw的练习32,来自他的书“以艰难的方式学习Python”。首先,这是练习中的代码:

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit

# also we can go through mixed lists too 
# notice we have %r since we don't know what's in it.
for i in change:
    print "I got %r" % i

# we can also build lists, first start with an empty one
elements = range(0, 6)

# then use the range function to do 0 to 5 counts
#for i in range(0, 6):
print "Adding %r to the list." % elements
# append is a function that lists understand
#elements.append(i)

# now we can print them out too
for i in elements:
    print "Element was: %r" % i

研究演习中,我偶然发现了一个简单的任务,即:

  

您是否可以避免完全在第22行进行for循环,而直接将range(0,6)直接分配给元素?

我对此进行了更改:

elements = []

for i in range(0, 6):
    print "Adding %r to the list." % elements
elements.append(i)

对此:

elements = range(0,6)

print "Adding %r to the list." % elements
elements.append(i)

在注释elements.append(i)之前,输出仍然是:

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'dimes'
I got 3
I got 'quarters'
Adding [0, 1, 2, 3, 4, 5] to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5
Element was: 'quarters'

为什么最后一行打印?或者,更确切地说,为什么append添加quarters?其背后的机制是什么?

P.S。我想知道为什么会得到这个/为什么会得到这个否决,因为我想在下次改进,所以我敢在SO提问。

2 个答案:

答案 0 :(得分:0)

调用for i in change:时,i是局部变量。这意味着它可以在整个本地范围内访问,而不仅仅是for块。

因此,在for块之后,i等于循环中的最后一个值。

答案 1 :(得分:-1)

在Python 2中,在for语句中初始化的变量可以忽略,甚至可以在for循环外使用。在for语法中启动的变量的作用域是局部作用域。这意味着,如果for循环位于函数中,则变量将具有函数的作用域。如果for循环位于模块中,则变量将具有模块本身的作用域。

当有elements.append(i)时,会将i的值附加到elements列表中。对于您而言,这是没有必要的,因为我们正在使用range函数。

请注意,在Python 3中仍然如此。在Python 3中,也可以从外部访问for语句中初始化的变量。

编辑:更新了最后一段,在此我声称Python 3不具备事实性的“功能”。避免“功能”的唯一方法是通过列表理解或通过闭包。