1. 程式人生 > 其它 >Python 05 | if語句 | 5.4 使用if語句處理列表

Python 05 | if語句 | 5.4 使用if語句處理列表

使用if語句處理列表

檢查特殊元素

使用之前的披薩店示例。製作披薩時會列印訊息,建立一個列表,其中包含顧客點的配料,使用迴圈指出新增到披薩中的配料。

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']

for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
print("\nFinished making your pizza.")

輸出:

>>>
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza.

如果青椒用完了,該如何處理?可在for迴圈中包含一條if語句:

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']

for requested_topping in requested_toppings:
    if requested_topping == 'green peppers': # 對披薩配料進行檢查
        print("Sorry, we are out of green peppers right now.") # 如果是青椒,就列印訊息
    else:
        print("Adding " + requested_topping + '.')
print("Finished making your pizza.")

輸出:

>>>
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza.

確定列表是不是空的

我們之前都假設列表中至少包含一個元素。但有時列表並不是一開始就有元素,我們需要做判斷。

下面在製作披薩之前判斷配料是否為空,如果是空的就確認是否點普通披薩,如果不是空的,就像上文那樣製作披薩。

requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + '.')
    print("\nFinished making your pizza.")
else:
    print("Are you sure you want a plain pizza?")

輸出:

>>>
Are you sure you want a plain pizza?

使用多個列表

顧客的需求五花八門。如果顧客要求新增炸薯條該怎麼辦?

下面看看如何拒絕奇葩要求。定義兩個列表,其中一個包含披薩店供應的配料,第二個包含顧客點的配料。對於requested_toppings中每個元素,檢查是否在供應的配料中,再決定是否新增它。

available_toppings = ['mushrooms', 'olives', 'green peppers',
                    'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print("Adding " + requested_topping + '.')
    else:
        print("Sorry, we don't hace " + requested_topping + '.')
print("\nFinished making your pizza.")

輸出:

>>>
Adding mushrooms.
Sorry, we don't hace french fries.
Adding extra cheese.

Finished making your pizza.

練習題

5-8 以特殊方式跟管理員打招呼

建立一個至少包含5個使用者名稱的列表,其中一個使用者名稱為'admin'。想象你要編寫程式碼,在每位使用者登入網站後列印一條問候訊息。遍歷使用者名稱列表,向每位使用者列印一條問候訊息。

  • 如果使用者名稱為'admin',就列印一條特殊的問候訊息,如"Hello admin, would you like to see a status report?"
  • 否則列印一條普通問候訊息,"Hello Eric, thank you for logging in again."
name_list = ['bob', 'will', 'hank', 'mason', 'admin']
for name in name_list:
    if name == 'admin':
        print("Hello " + name.title() + ", would you like to see a status report?")
    else:
        print("Hello " + name.title() + ", thank you for logging in again.")

輸出:

>>>
Hello Bob, thank you for logging in again.
Hello Will, thank you for logging in again.
Hello Hank, thank you for logging in again.
Hello Mason, thank you for logging in again.
Hello Admin, would you like to see a status report?

5-9 處理沒有使用者的情形

在5-8中新增if語句,檢查使用者列表是否為空。

  • 如果為空,列印訊息"We need to find some users!"
  • 刪除列表中所有使用者,確定將列印正確的訊息。
name_list2 = []
if name_list2:
    print('')
else:
    print("We need to find some users.")

輸出:

>>>
We need to find some users.

5-10 檢查使用者名稱

模擬網站確保每位使用者的使用者名稱都獨一無二

  • 建立一個至少包含5個使用者的列表,命名為current_users
  • 再建立一個包含5個使用者的列表,命名為new_users,確保其中有一兩個使用者包含在current_users中
  • 遍歷列表new_users,對於其中每個使用者名稱,檢查是否被使用。如果是,列印一條訊息,換一個名字。否則,列印訊息,這個名字沒被使用。
  • 確保比較時不區分大小寫,即使用者名稱'John'被使用,應拒絕'JOHN'。
current_users = ['bob', 'will', 'hank', 'mason', 'admin']
new_users = ['BOB', 'will', 'tom', 'jack', 'sam']

for name in new_users:
    if name.lower() in current_users:
        print(name.title() + " has been taken, please change a new one.")
    else:
        print(name.title() + " is available.")

輸出:

>>>
Bob has been taken, please change a new one.
Will has been taken, please change a new one.
Tom is available.
Jack is available.
Sam is available.

5-11 序數

序數表示位置,如1st和2nd,大多數序數都以th結尾,只有1、2和3例外

  • 在一個列表中儲存1-9
  • 遍歷列表
  • 在迴圈中使用if-elif-else結構,列印每個數字對應的序數。輸出內容應該為1st、2nd、3rd、4th、5th、6th、7th、8th和9th,但每個序數都獨佔一行
for number in range(1, 10):
    if number == 1:
        print(str(number) + "st\n")
    elif number == 2:
        print(str(number) + "nd\n")
    elif number == 3:
        print(str(number) + "rd\n")
    else:
        print(str(number) + "th\n")

輸出:

>>>
1st

2nd

3rd

4th

5th

6th

7th

8th

9th