《Python 编程从入门到实践》———— 传递列表

 向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。这就为我们使用函数来提高处理列表的效率提供了可能。

# 输出
user_name = ['Tom','Jerry','Hank']
def greet(user_name):
    for name in user_name:
        print('Hello ' + name.title())

greet(user_name)

# 输出
Hello Tom
Hello Jerry
Hello Hank

 将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。这个程序还演示了这样一种理念,即每个函数都应只负责一项具体的工作。

# 输入
user_name = ['Tom','Jerry','Hank']
comfirmed_user = []
def greet(user_name):
    while user_name:
        temp = user_name.pop()
        comfirmed_user.append(temp)
    print(comfirmed_user)

greet(user_name)
for comfirmed in comfirmed_user:
    print(comfirmed.upper())


# 输出
['Hank', 'Jerry', 'Tom']
HANK
JERRY
TOM

传递任意数量的实参
 有时候,我们不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。形参名 *userinfos 中的星号让 Python 创建一个名为 userinfos 的空元组,并将收到的所有值都封装到这个元组中。

# 输入
def print_userinfo(*userinfos):
    print("The user info include :" + userinfos)

print_userinfo('Name')
print_userinfo('Name','Sex','Age','Job')

# 输出
Traceback (most recent call last):
  File "C:\script\Function.py", line 4, in <module>
    print_userinfo('Name')
  File "C:\script\Function.py", line 2, in print_userinfo
    print("The user info include :" + userinfos)
TypeError: can only concatenate str (not "tuple") to str

 函数体内的 print 语句通过生成输出来证明 Python 能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此。

# 输入
def print_userinfo(*userinfos):
    for userinfo in userinfos:
        print("The user info include :" + userinfo)

print_userinfo('Name','Sex','Age','Job')

# 输出
The user info include :Name
The user info include :Sex
The user info include :Age
The user info include :Job

结合使用位置实参和任意数量实参
 如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

# 输入
def print_userinfo(name,*userinfos):
    print('The use name is :' + name)
    for userinfo in userinfos:
        print("The user info include :" + userinfo)

print_userinfo('Youth','Sex','Age','Job')
print_userinfo('Youth','Sex','Age')

# 输出
The use name is :Youth
The user info include :Sex
The user info include :Age
The user info include :Job
The use name is :Youth
The user info include :Sex
The user info include :Age

任意数量的关键字实参
 有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。形参 **user_info 中 的 两个星号 让Python创建一个名为user_info 的空字典,并将收到的所有名称—值对都封装到这个字典中。在这个函数中,可以像访问其他字典那样访问 user_info 中的名称键值对。

# 输入
def print_userinfo(name,**userinfos):
    userinfo = {}
    userinfo['Name'] = name
    for key,value in userinfos.items():
        userinfo[key] = value
    return userinfo

userinfo = print_userinfo('Youth',sex = 'Male',age = '18')
print(userinfo)

# 输出
{'Name': 'Youth', 'sex': 'Male', 'age': '18'}

 编写函数时,你可以以各种方式混合使用位置实参、关键字实参和任意数量的实参。知道这些实参类型大有裨益,因为阅读别人编写的代码时经常会见到它们。

Guess you like

Origin blog.csdn.net/qq_42957717/article/details/118070540