四时宝库

程序员的知识宝库

列表的循环遍历与嵌套(什么叫列表循环)

while

# while 循环遍历,输出列表中的数据
name_list = ["TOM", "Rose", "Tony"]

i = 0
while i < len(name_list):
    print(name_list[i])
    i += 1

for

# for 循环遍历,输出列表中的数据
name_list = ["TOM", "Rose", "Tony"]

for i in name_list:
    print(i)
'''
输出:
TOM
Rose
Tony
'''

列表嵌套

所谓列表嵌套指的就是一个列表里面包含了其他的子列表。

food_list = [['apple', 'orange', 'banana'], ['water', 'juice', 'tea'], ['radish', 'cabbage', 'Beans']]

# 如何查找"tea"
print(food_list[1])    # 查找到tea所在的列表,输出['water', 'juice', 'tea']
print(food_list[1][2])  # 根据查找到的列表在输出字列表中的元素tea

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接