使用函数对列表中的元素进行处理。
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[:])调用函数的副本