Python3 遍历列表、字典和元组方式总结

# 列表\字典\元组 遍历方式
def loop(request):
    # 元组遍历方式一:for in
    tupe_one = ('1', '2', '3', '4')
    for value in tupe_one:
        print(value)
    # 元组遍历方式二:内置函数enumerate()
    tupe_tow = ('1', '2', '3', '4')
    for index, value in enumerate(tupe_tow):
        print("下标:%s   值:%s" % (str(index), value))
    # 元组遍历方式三:使用range()函数
    tupe_three = ('1', '2', '3', '4')
    for index in range(len(tupe_three)):
        print(tupe_three[index])
    # 元组遍历方式四: 使用iter()内置函数,返回迭代器对象
    tupe_four = ('1', '2', '3', '4')
    for value in iter(tupe_four):
        print(value)

    # 列表遍历方式一:for in
    list_one = ('1', '2', '3', '4')
    for value in list_one:
        print(value)
    # 列表遍历方式二:内置函数enumerate()
    list_tow = ('1', '2', '3', '4')
    for index, value in enumerate(list_tow):
        print("下标:%s   值:%s" % (str(index), value))
    # 列表遍历方式三:使用range()函数
    list_three = ('1', '2', '3', '4')
    for index in range(len(list_three)):
        print(list_three[index])
    # 列表遍历方式四: 使用iter()内置函数,返回迭代器对象
    list_four = ('1', '2', '3', '4')
    for value in iter(list_four):
        print(value)

    # 字典遍历方式一:for in
    dict_one = {"one": 1, "two": 2, "three": 3}
    for value in dict_one:
        print("K:%s   Value:%d" % (value, dict_one[value]))
    # 字典遍历方式二:使用dict的keys()方法
    dict_two = {"one": 1, "two": 2, "three": 3}
    for key in dict_two.keys():
        print("K:%s   Value:%d" % (key, dict_two[key]))
    # 字典遍历方式三: 使用dict的values()方法
    dict_three = {"one": 1, "two": 2, "three": 3}
    for value in dict_three.values():
        print("value:" + str(value))
    # 字典遍历方式四: 使用dict的items()方法
    dict_four = {"one": 1, "two": 2, "three": 3}
    for item in dict_four.items():
        print(item)
    # 字典遍历方式五: 使用dict的items()方法,然后直接解包元组
    dict_five = {"one": 1, "two": 2, "three": 3}
    for key, value in dict_five.items():
        print(key + ":" + str(value))
    return response_success(message='列表、字典、元组遍历方式验证')

运行结果:

1
2
3
4
下标:0   值:1
下标:1   值:2
下标:2   值:3
下标:3   值:4
1
2
3
4
1
2
3
4
1
2
3
4
下标:0   值:1
下标:1   值:2
下标:2   值:3
下标:3   值:4
1
2
3
4
1
2
3
4
K:one   Value:1
K:two   Value:2
K:three   Value:3
K:one   Value:1
K:two   Value:2
K:three   Value:3
value:1
value:2
value:3
('one', 1)
('two', 2)
('three', 3)
one:1
two:2
three:3

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值