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