Java教程

[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: = 与 +=
    • bonus 2: append 与 extend
  • Equality and Identity
    • List
    • strings/numbers
  • Scope

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

这篇关于[2021 Spring] CS61A 学习笔记 lecture 14 List mutation + Identity + Nonlocal的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!