溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python傳遞列表的方法

發(fā)布時(shí)間:2020-08-06 11:08:54 來源:億速云 閱讀:196 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Python傳遞列表的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

傳遞列表

def greet_users(names):
    for name in names:
        mag = "Hello, " + name.title() + "!"
        print(mag)
user_names = ['hannah', 'bob', 'margot']
greet_users(user_names)

運(yùn)行結(jié)果:

Hello, Hannah!
Hello, Bob!
Hello, Margot!

1. 在函數(shù)中修改列表

# 創(chuàng)建一個(gè)列表,其中包含一些要打印的設(shè)計(jì)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模擬打印每個(gè)設(shè)計(jì),直到?jīng)]有未打印的設(shè)計(jì)為止,打印后移至completed_models中
while unprinted_designs:
    current_design = unprinted_designs.pop()
    # 模擬根據(jù)設(shè)計(jì)制作打印模型的過程
    print("Printing model: " + current_design)
    completed_models.append(current_design)
# 顯示打印好的模型
print("\nThe following models have been printed:")
print(completed_models)

運(yùn)行結(jié)果:

Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case
The following models have been printed:
['dodecahedron', 'robot pendant', 'iphone case']

 用函數(shù)如何表達(dá)上述代碼的意思呢?

def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

當(dāng)print_models函數(shù)調(diào)用之后,列表completed_models已經(jīng)不是最初定義的空,所有列表unprinted_designs中的元素已轉(zhuǎn)移至列表completed_models,接下來調(diào)用show_completed_models函數(shù)就將列表completed_models中的元素都打印出來。

2. 禁止函數(shù)修改列表

上述的例子中print_models函數(shù)調(diào)用之后,列表unprinted_designs中的元素均已移除,此時(shí)的列表為空。但若想保留列表中的元素呢?

print_models(unprinted_designs[:], completed_models)

用切片法 [ : ] 創(chuàng)建列表副本,函數(shù)調(diào)用時(shí)使用的是列表的副本,而不是列表本身,此時(shí)函數(shù)中對列表做的修改不會(huì)影響到列表unprinted_designs。

關(guān)于Python傳遞列表的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI