Python学习笔记(十)- 赋值,表达式和打印(Assignments, Expressions, and Prints)

1.列出三种可以将三个变量赋给同一个值的方法
答:您可以使用多目标分配【multipule-target assignments】(A = B = C = 0),序列赋值【sequence assignment】(A, B, C = 0, 0, 0),或者三行多个赋值语句(A = 0, B = 0 和 C =0)。使用后一种方法,如第10章所介绍的,您还可以通过用分号将三个单独的语句串在同一行上(A= 0; B = 0; C = 0)。

2.当把三个变量赋给一个可变对象,你需要注意些什么?
答:如果你用下面这样赋值:
A = B = C = []
所有的名字引用了相同的对象,所以其中一个改变了(例如,A.append(99))将会影响其它两个。这仅适用于对可变对象(如列表和字典)的就地更改;对于不可变对象(如数字和字符串),此问题与此无关。

3.L = L.sort() 哪里有问题?
答:列表方法 sort 像 append 操作一样,它对列表进行了就地更改——返回值为None,而不是它更改的列表。这个赋值操作返回给L,并把L设定为None,而不是排序后的列表。正如本书前面和后面所讨论的(例如,第8章),一个较新的内置函数,sorted,排序任何序列然后返回排列结果的新列表;因为这不是就地更改,所以可以将其结果有意义地赋值给名称。

4.如何使用 print 操作将文本发送到外部文件(external file)?
答:将单个 print 操作打印到文件中,你可以使用 Python 3.X 的 print(X, file=F) 函数调用形式,使用 Python 2.X 的扩展 print >> file, X 语句形式,或在打印之前将 sys.stdout 赋值给手动打开的文件,然后恢复原始文件。您还可以将程序的所有打印文本重定向到系统shell中具有特殊语法的文件,但这不在Python的范围之内。

标注:转载《Learning Python 5th Edition》[奥莱理]

1. Name three ways that you can assign three variables to the same value.
2. Why might you need to care when assigning three variables to a mutable object?
3. What’s wrong with saying L = L.sort()?
4. How might you use the print operation to send text to an external file?


1. You can use multiple-target assignments (A = B = C = 0), sequence assignment(A, B, C = 0, 0, 0), or multiple assignment statements on three separate lines (A= 0, B = 0, and C = 0). With the latter technique, as introduced in Chapter 10, you can also string the three separate statements together on the same line by separatingthem with semicolons (A = 0; B = 0; C = 0).
2. If you assign them this way:A = B = C = []all three names reference the same object, so changing it in place from one (e.g.,A.append(99)) will affect the others. This is true only for in-place changes to mutable objects like lists and dictionaries; for immutable objects such as numbers and strings, this issue is irrelevant.
3. The list sort method is like append in that it makes an in-place change to the subject list—it returns None, not the list it changes. The assignment back to L sets L to None, not to the sorted list. As discussed both earlier and later in this book (e.g., Chapter 8), a newer built-in function, sorted, sorts any sequence and returns a new list with the sorting result; because this is not an in-place change, its result can be meaningfully assigned to a name.
4. To print to a file for a single print operation, you can use 3.X’s print(X, file=F) call form, use 2.X’s extended print >> file, X statement form, or assign sys.stdout to a manually opened file before the print and restore the original after. You can also redirect all of a program’s printed text to a file with special syntax in the system shell, but this is outside Python’s scope.

猜你喜欢

转载自blog.csdn.net/Enderman_xiaohei/article/details/87384486
今日推荐