python学习笔记(七)之函数传递列表

使用函数对列表中的元素进行处理。

def greet_users(names):
    '''向列表中的用户发出问候'''
    for name in names:
        msg = "hello, " + name.title() + "!"
        print(msg)
user_names = ['a张三', '赵四', '王二']
greet_users(user_names)


----------
Result:
    hello, 张三!
    hello, 赵四!
    hello, 王二!   

1.在函数中修改列表
不使用函数时,

**unprinted_designs = ['iphone', 'robot', 'cars']
completed_models = []
while unprinted_designs:
    current_designed = unprinted_designs.pop();
    print("Printing models: " + current_designed)
    completed_models.append(current_designed)
print("\nThe following models have been printed:")
for model in completed_models:
    print(model)


----------
**Result:**

Printing models: cars
Printing models: robot
Printing models: iphone

The following models have been printed:
cars
robot
iphone

接下来使用两个函数实现上述的功能。
第一个函数用来打印第一个列表中的数据,同时将元素移动到第二个空列表中。第二个函数用来打印空列表中的数据。

def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_designed = unprinted_designs.pop()
        print("Printing models: " + current_designed)
        completed_models.append(current_designed)
def show_comleted_models(completed_models):
    for model in completed_models:
        print(model)
unprinted_designs = ['iphone', 'robot', 'cars']
completed_models = []
print_models(unprinted_designs, completed_models)
show_comleted_models(completed_models)


----------
**Result**
Printing models: cars
Printing models: robot
Printing models: iphone
cars
robot
iphone

2.禁止函数修改列表
function(list_name[:])调用函数的副本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值