python从零开始--13 元组、列表、字典和字符串的遍历

  前面有一章专门记录了元组、列表和字典的相关概念和基本用法;今天读了廖雪峰的文章后,感觉要增加一篇如何遍历的笔记。

  对于元组,列表,字符串基础的遍历方式是类似,如下方的代码,下面的代码将元素一个个的遍历并进行打印。

my_list = [1, 3, 5, 6, 'kk']
my_tuple = ('u', 'v', 7)
my_str = "It's awesome!"

for item in my_list:
    print(item)

for item in my_tuple:
    print(item)

for char_ in my_str:
    print(char_)

  对于序列含有子序列的,还可以用如下的方式遍历:

my_com_list = [(1, 2), ('y', 'z'), (8, 10)]
for sub_item1,sub_item2 in my_com_list:
    print("{}<=>{}".format(sub_item1,sub_item2))
D:\pythonProjects\venv\Scripts\python.exe D:/pythonProjects/100Prac/54.py
1<=>2
y<=>z
8<=>10

  对于字典的遍历:

student_dict = {"张三": 15, "李四": 14, "王五": 16}

for key in student_dict:
    print("{}<=>{}".format(key, student_dict[key]))
王五<=>16
张三<=>15
李四<=>14

  字典的另外一种遍历方法,这种方法利用了字典的items()方法,它返回可遍历的元组数组:

student_dict = {"张三": 15, "李四": 14, "王五": 16}

for key,val in student_dict.items(): # items() 方法以列表返回可遍历的(键, 值) 元组数组。
    print("{}<=>{}".format(key, val))




猜你喜欢

转载自blog.csdn.net/pansc2004/article/details/80242479