1.遍历
字符串、列表、元祖遍历一模一样
my_str = "hello world"
my_list = ["hello", "world"]
my_tuple = ("hello", "world")
# 最普通的遍历
for i in my_list:
print(i) # 依次打印里面的元素
# 带下标
for index, value in enumerate(my_list):
print(index) # 依次打印下标
print(value) # 依次打印里面的元素
2.字典
<1> 遍历字典的key(键)
my_dict = {"name": "路飞", "sex": "男", "age": 18}
for key in my_dict.keys():
print(key) # 依次打印字典里的key
<2> 遍历字典的value(值)
<2> 遍历字典的value(值)
my_dict = {"name": "路飞", "sex": "男", "age": 18}
for value in my_dict.values():
print(value) # 依次打印字典里的value
<3> 遍历字典的项(元素)
my_dict = {"name": "路飞", "sex": "男", "age": 18}
for item in my_dict.items():
print(item) # 依次打印字典里项, 放在元祖里 ("name", "路飞")
<3> 遍历字典的key-value(键值对)
my_dict = {"name": "路飞", "sex": "男", "age": 18}
for key, value in my_dict.items():
print(key) # 依次打印字典里的key
print(value) # 依次打印字典里的value