2025/12/29

6 阅读4分钟

度过了个超级繁忙的周末,忙着布置孩子的生日会,带他们玩,见缝插针的找时间去打球。 今天复习了列表的剩余部分基础&if语句。 4. 复制列表

  • 巧妙使用切片来复制:
   my_foods=['pizza','falafel','carrot cake']
    friend_foods=my_foods[:]
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    print("My favorite foods are:")
    print(my_foods)
    print("\nMy friend's favorite foods are:")
    print(friend_foods) 

==注意== :==若是直接采用赋值的方法,实际两个变量指向的是同一个列表,再用append分别追加值也将得到一样的列表,== ==非我们所期望的==

    my_foods=['pizza','falafel','carrot cake']
    friend_foods=my_foods
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    print("My favorite foods are:")
    print(my_foods)
    print("\nMy friend's favorite foods are:")
    print(friend_foods)
    # 》 My favorite foods are:
    # 》 ['pizza','falafel','carrot cake','cannoli','ice cream']
    
    # 》My friend's favorite foods are:
    # 》['pizza','falafel','carrot cake','cannoli','ice cream']
    
    print(f"The first three items in the list are:")
    print(my_foods[:3])
    long=len(my_foods)
    print(long)
    n=int(long/2)
    print(n)
    print(f"\nThree items from the middle of the list are:")
    print(my_foods[n-1:n+2]) # 这里注意索引开始值为n-1
    print(f"\nThe last three items in the list are:")
    print(my_foods[-3:]) 
    
    》The first three items in the list are:
    》['pizza', 'falafel', 'carrot cake']
    》42
   
    》Three items from the middle of the list are:
    》['falafel', 'carrot cake', 'cannoli']
    
    》The last three items in the list are:
    》['falafel', 'carrot cake', 'cannoli']
  1. 元组
  • 不可修改的列表称为元组(tuple),用()来表示;适用于列表的用法同样适用于元组
  • 严格来说元组是由逗号标识的,因此如果要定义只包含一个元素的元组,必须再元素后加上逗号,例如==my_t=(3,)
  • 无法单独给元组中的单个元素进行赋值或其他修改,但是可以给==元组这个变量进行赋值修改

if语句 ==在进行循环前,确定列表非空非常重要:

requested_topping=[]
if requested_toppings:
	for requested_topping in requested_topping:
		print(f"Adding {requested_topping}.")
	print("\nFinished making your pizza!")
else:
	print("Are you sure you want a plain pizza?")
# if 语句中将列表名用作条件表达句时,python将在列表至少包含一个元素时返回true。
  • 假设一个列表有五个元素:用if语句检查列表是否为空,如果为空,则打印消息“请添加用户",否者删除列表中的所有用户名,确认将打印正确的消息。
if not usernames: # 或者if len(usernames)==0:
	print("请添加用户")
else:
	usernames.clear() # 或者usernames=[]
	print("所有用户名已成功删除")
	print(f"确认:当前用户列表为:{usernames}")
def manage_users(usernames):
	if not usernames:
		print("请添加用户")
		return usernames
	else:
		print(f"正在删除{len(usernames)}个用户...")
		usernames.clear()
		print("所有用户名已成功删除")
		print(f"确认:当前用户列表为:{usernames}")
		return usernames

==这里出现了一个错误用法,导致在执行删除时,出现了索引混乱,导致循环未执行完毕就停止了:

us=['pp','cc','dd','ee','admin']
if us:
    for i in us:
        del us[0]
        print(us)
else:
    print("We need to find some users!")
   # 》['cc', 'dd', 'ee', 'admin']
   # 》['dd', 'ee', 'admin']
   # 》['ee', 'admin'] # 循环到这里就停止了,索引混乱导致没有彻底删除

练习:检查用户名 按照下面的说明编写一个程序,模拟网站如何确保每个用户的用户名都独一无二。创建一个至少包含 5 个用户名的列表,并将其命名为current_users。再创建一个包含 5 个用户名的列表,将其命名为new_users,并确保其中有一两个用户名也在列表current_users 中。 遍历列表 new_users,检查其中的每个用户名是否已被使用。如果是,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。确保比较时不区分大小写。换句话说,如果用户名 'John',已被使用,应拒绝用户名 'JOHN'。

current_users=['pp','cc','dd','ee','admin']
new_users=['aa','bb','CC','PP']
for i in new_users:
    if i.lower() in [p.lower() for p in current_users]:
        print(f"您输入的用户名是{i},该用户名已被使用,需要输入别的用户名")
    else:
        print(f"您输入的用户名是{i},这个用户名未被使用")
# 》您输入的用户名是aa,这个用户名未被使用
# 》您输入的用户名是bb,这个用户名未被使用
# 》您输入的用户名是CC,该用户名已被使用,需要输入别的用户名
# 》您输入的用户名是PP,该用户名已被使用,需要输入别的用户名