全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1156 1
2015-01-26
  • Name three ways that you can assign three variables to the same value.

  • Why might you need to care when assigning three variables to a mutable object?

  • What’s wrong with saying L = L.sort()?

  • How might you use the print operation to send text to an external file?



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-1-26 00:10:28

Answer

  • 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 separating them with semicolons (A = 0; B = 0; C = 0).

  • 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.

  • 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 Lto 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.

  • 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 assignsys.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.


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群