• Python学习笔记_List&Tuple


    Someting about Lists mutation

    ###################################
    # Mutation vs. assignment
    
    
    ################
    # Look alike, but different
    
    a = [4, 5, 6]
    b = [4, 5, 6]
    print "Original a and b:", a, b
    print "Are they same thing?", a is b
    
    a[1] = 20
    print "New a and b:", a, b
    print
    
    ################
    # Aliased
    
    c = [4, 5, 6]
    d = c
    print "Original c and d:", c, d
    print "Are they same thing?", c is d
    
    c[1] = 20
    print "New c and d:", c, d
    print
    
    ################
    # Copied
    
    e = [4, 5, 6]
    f = list(e)
    print "Original e and f:", e, f
    print "Are they same thing?", e is f
    
    e[1] = 20
    print "New e and f:", e, f
    print
    
    
    ###################################
    # Interaction with globals
    
    
    a = [4, 5, 6]
    
    def mutate_part(x):  #注:这里的a默认为global
        a[1] = x
    
    def assign_whole(x): 
        a = x
    
    def assign_whole_global(x):
        global a
        a = x
    
    mutate_part(100)
    print a
    
    assign_whole(200)
    print a
    
    assign_whole_global(300)
    print a
    View Code

    这里的赋值需要注意:

    b = a ,则a, b指向同一块内存,对a[1]或者b[1]赋值, 都可以改变这个list;

    b = list(a), 则a, b指向不同的内存。

    又如:

    x = range(5)

    y = x

    y = [0, 1, 10, 3, 4]

    这时,y又会被分配一块内存。x, y不指向同一块内容了。

    global  vs  local

    mutate_part(x)这个函数对a[1]进行了更改,这里a被默认为global;

    assign_whole(x)中a则是local。

    assign_whole_global(x)中想对全局变量进行更改,所以加上global关键字

    a = range(5)
    def mutate1(b):
        b[3] = 100
        print b #[0, 1, 2, 100, 4]
    mutate1(a)
    print a[3]# 100
      
        
    a = range(5)
    def mutate1(a):
        b[3] = 100 #NameError: name 'b' is not defined
        print b 
    mutate1(a)
    print a[3]
    
    
    a = range(5)
    def mutate1(b):
        a[3] = 100
        print b #[0, 1, 2, 100, 4], 这里b是a的副本
    mutate1(a)
    print a[3]# 100
    
    
    a = range(5)
    def mutate1(a):
        a[3] = 100
        print a #[0, 1, 2, 100, 4]
    mutate1(a)
    print a[3]# 100

     其实,只要mutate()传递的是a这个global,则函数中对a[]做的赋值操作,均是对全局global的操作。

    lists  & tuples(多元组)

    difference: lists are mutable; tuples are immutable, strings are the same as tuples, immutable.

    list的‘‘+’’, 可不是向量的对应项相加的意思哦!

  • 相关阅读:
    ajax中文乱码问题的总结
    JQuery中$.ajax()方法参数详解
    Jquery的parent和parents(找到某一特定的祖先元素)
    div节点的操作(添加,删除,替换,克隆)
    js 刷新页面
    ADO.NET 体系结构
    数据访问技术介绍
    WebForm页面数据绑定总结
    sql 智能提示
    用TTTAttributedLabel创建变化丰富的UILabel
  • 原文地址:https://www.cnblogs.com/beatrice7/p/4029450.html
Copyright © 2020-2023  润新知