Python学习笔记:列表、元组、字典的遍历

本文介绍了Python中遍历列表、元组和字典的方法,包括使用for循环遍历元素,以及如何分别获取字典的key、value和key-value对。

一、列表遍历

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]

(当笔记用,自己忘了的时候能翻翻)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值