1. 程式人生 > 其它 >[2021 Spring] CS61A 學習筆記 lecture 14 List mutation + Identity + Nonlocal

[2021 Spring] CS61A 學習筆記 lecture 14 List mutation + Identity + Nonlocal

主要內容:
列表的建立、更新、方法(python基礎課程均有講解,也可以檢視菜鳥教程等)
is 和 == 的區別
nonlocal 和 global(可以參考parent frame)

目錄

List creation, List mutation, List methods

bonus 1: = 與 +=

b = b + [8, 9]改變了b的指向,b += [8, 9]

沒有改變。(老師只提出了這個現象,沒有解釋原因,philosophy)

bonus 2: append 與 extend

  • append() adds a single element to a list
  • extend() adds all the elements in one list to a list
  • pop() removes and returns the last element
  • remove() removes the first element equal to the argument
    t為列表,t的變化會影響到s.append(t),但是不會影響到s.extend(t)
    .

Equality and Identity

  • Identity : exp0 is exp1
    • evaluates to True if both exp0 and exp1 evaluate to the same object
  • Equality: exp0 == exp1
    • evaluates to True if both exp0 and exp1 evaluate to objects containing equal values
      對於列表和字串/數字來說不同,可能原因:列表是可變型別,字串和數字是不可變型別。

List

注意:兩個各自定義的列表指向並不相同,所以identity=False,只有值相同。(對於字串/數字可能不成立,identity=True)

a = ["apples" , "bananas"]
b = ["apples" , "bananas"]
c = a
if a == b == c:
    print("All equal!")
a[1] = "oranges"
if a  is c  and  a == c:
    print("A and C are equal AND identical!")
if a == b:
    print("A and B are equal!") # Nope!
if b == c:
    print("B and C are equal!") # Nope!

strings/numbers

以下全部為True:

a = "orange"
b = "orange"
c = "o"  +  "range"
print(a  is b)
print(a  is c)
a = 100
b = 100
print(a  is b)
print(a  is 10 *  10)
print(a == 10 *  10)
a = 100000000000000000
b = 100000000000000000
print(a  is b)
print(100000000000000000 is 100000000000000000 )

Scope

scope rules