zoukankan      html  css  js  c++  java
  • More about Parameter Passing in Python(Mainly about list)

      我之前写了一篇关于Python参数传递(http://www.cnblogs.com/lxw0109/p/python_parameter_passing.html)的博客,

    写完之后,我发现我在使用list的时候(我想在函数中改变实参),感觉使用文章中提到的传参理解还是有点儿迷惑和混乱

    所以在此关于list的参数传递,再做一下补充和说明,这些是我个人的理解,如果您感觉有任何疑问或者不同的观点,非常

    感谢您与我讨论,谢谢。

    #!/usr/bin/python
    #coding:utf-8
    #File: listParaPass.py
    #Author: lxw
    #Time: 2014-04-19
    #Usage: Learn more about parameter passing in Python.
    
    # 所以得到的结论就是:想改变实参,则实参不能以分片的形式传递,且函数内部须以分片的形式操作
    
    def change(x):
        x[:] = ['o', 'k']
        print('x is {0}'.format(x))
    
    #1:
    a = [10, 20, 30]
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    change(a)                        # x is ['o', 'k']
    print('a is {0}'.format(a))        # a is ['o', 'k']
    
    #2:
    a = [10, 20, 30]
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    # 想改变实参,则不能传分片;使用分片传,不会影响到实参。
    change(a[:])                    # x is ['o', 'k']
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    
    print('')
    print('')
    
    def change1(x):
        # 与上面的例子对比得到如下结论:
        # 想改变实参(前提实参传的不能是分片),则函数内须用分片;若函数内不使用分片,则不会影响到实参。
        x = ['o', 'k']
        print('x is {0}'.format(x))
    
    #1:
    a = [10, 20, 30]
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    change1(a)                        # x is ['o', 'k']
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    
    #2:
    a = [10, 20, 30]
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    change1(a[:])                    # x is ['o', 'k']
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    
    
    print('')
    print('')
    
    def change2(x):
        x[1:3] = ['o', 'k']
        print('x is {0}'.format(x))
    
    #1:
    a = [10, 20, 30]
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    change2(a)                        # x is [10, 'o', 'k']
    print('a is {0}'.format(a))        # a is [10, 'o', 'k']
    
    #2:
    a = [10, 20, 30]
    print('a is {0}'.format(a))        # a is [10, 20, 30]
    change2(a[:])                    # x is [10, 'o', 'k']
    print('a is {0}'.format(a))        # a is [10, 20, 30]

     注:把索引(如:a[1])也归入分片操作。

  • 相关阅读:
    #Leetcode# 338. Counting Bits
    POJ 3614(Sunscreen)
    POJ 2392(Space Elevator)
    POJ 3666(Making the Grade)
    Coursera吴恩达《构建机器学习项目》课程笔记 -- 机器学习策略(下)
    Coursera吴恩达《构建机器学习项目》课程笔记-- 机器学习策略(上)
    深度学习入门--Stanford CS230--学习笔记
    POJ 1065 (Wooden Sticks)
    POJ 1742(Coins)
    C++ 按位与(&)、或(|)、异或(^)等操作符
  • 原文地址:https://www.cnblogs.com/lxw0109/p/parameter_passing_in_Python.html
Copyright © 2011-2022 走看看