Files
2025PY/day16/04-元祖的应用.py
2025-05-22 16:50:44 +08:00

42 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 1.创建两个元组,分别包含城市名和对应的国家名,将它们组合成一个列表,格式为"城市 - 国家"。
# 第一步:创建两个元组(国家名,城市名)
country = ('中国','日本','韩国')
city = ('北京','东京','首尔')
# 第二步:进行组合
# 两个元组相互对应的,使用相同的索引进行遍历(0,1,2)
# 将它们组合成一个列表
list = []
for index in range(0,len(country)): # 通过索引遍历对应的值
# 格式为"城市 - 国家"
# city[index]:城市 country[index]:国家
list.append(city[index] + '-' + country[index]) #将拼接好的格式追加到列表中
# print(list) # ['北京-中国', '东京-日本', '首尔-韩国']
# 2.创建一个包含3个元组的列表每个元组包含一个人的姓名和年龄。将所有人的姓名提取到一个新的列表中。
# 第一步创建一个包含3个元组的列表姓名和年龄
list = [('zhangsan',20),('lisi',18),('wangwu',30)]
# 第二步:将所有人的姓名提取到一个新的列表中
# 直接循环这个列表
# 遍历列表,列表的每一个元素都是元组,可以对元组用逗号进行直接获取
# a,b,c = (1,2,3) # 将1给a2给b3给c ,逗号进行多个变量的赋值
# print(a,b,c)# 1 2 3
# a,b,c = [4,5,6]
# print(a,b,c) # 4,5,6 逗号进行多个变量的赋值
new_list = []
for name,age in list:
new_list.append(name)
print(new_list) # ['zhangsan', 'lisi', 'wangwu']
# 准备的列表
list = [('zhangsan',20),('lisi',18),('wangwu',30)]
new_list = [] # 准备的新列表,接收列表中的姓名
for item in list : # item:列表中的每一个元素list:列表对象
new_list.append(item[0])
print(new_list) # ['zhangsan', 'lisi', 'wangwu']