一、列表遍历
listt = ['hello world', 100, 123.56, ['string'], True]
for xx in listt:
print(xx)
打印:
hello world
100
123.56
['string']
True二、元组遍历
同列表
tupp = ('hello world', 100, 123.56, ['string'], False)
for xx in tupp:
print(xx)
打印:
hello world
100
123.56
['string']
False三、字典遍历
dictt = {
"key1":"hello python3",
"key2":100,
"key3":True,
"key4":listt
}
for xx in dictt:
print(xx)
打印:
key1
key2
key3
key4由上可知,默认情况下,字典迭代的是key,单独迭代value可以用.values():
for xx in dictt.values():
print(xx)
打印:
hello python3
100
True
['hello world', 100, 123.56, ['string'], True]key 和 value同时迭代可以用.items():
for k,v in dictt.items():
print(f"key = {k}, value = {v}")
打印:
key = key1, value = hello python3
key = key2, value = 100
key = key3, value = True
key = key4, value = ['hello world', 100, 123.56, ['string'], True]或者可以用终极笨办法,先获取字典的key列表,用key来遍历字典:
key_list = list(dictt.keys())
# value_list = list(dictt.values())
print(key_list)
for xx in key_list:
print(dictt[xx])
打印:
['key1', 'key2', 'key3', 'key4']
hello python3
100
True
['hello world', 100, 123.56, ['string'], True](当笔记用,自己忘了的时候能翻翻)
本文介绍了Python中遍历列表、元组和字典的方法,包括使用for循环遍历元素,以及如何分别获取字典的key、value和key-value对。
4424





