【Python数据结构的遍历】------- PYTHON基础13

本文介绍了如何遍历Python中的数据结构,包括字符串、一维和二维列表以及字典。对于一维列表,展示了基础遍历以及找出最大值和其索引的方法。在二维列表部分,演示了如何访问每个元素。最后,讨论了遍历字典的键和键值对。
摘要由CSDN通过智能技术生成

一、数据结构的遍历

1. 字符串的遍历

str1 = "dashima"
for i in str1:
    print(i)

输出

d
a
s
h
i
m
a

2. 列表的遍历

2.1. 遍历一维列表

list1 = [12, 'python', 9, 'C++', '2021', 'dashima', -6]
for i in list1:
    print(i)

2.2. 遍历一维列表,取出最大的数字以及对应的索引

list1 = [12, 0, 9, 17, 20, 21, 76, 65, 77, 56, 46]
maxnum = list1[0]
ind = 0
k = 0
for i in list1:
    if i > maxnum:
        maxnum = i
        ind = k
    k += 1
print("maxnum = ", maxnum)
print("index = ", ind)

输出

maxnum =  77
index =  8

2.3. 遍历二维列表

list2d = [
         [1, 3, 5],
         [2, 4, 6],
         [5, 2, 0],
         [7, 9, 8],
          ]
for i in list2d:
    print(i)

# 通过二层for循环逐一访问二维列表里的每一个元素:
for i in list2d:
    for j in i:
        print(j)

输出

[1, 3, 5]
[2, 4, 6]
[5, 2, 0]
[7, 9, 8]
1
3
5
2
4
6
5
2
0
7
9
8

3. 字典的遍历

访问字典的键值:

dict1 = {"name": "小明", "birth": "2005/06", "code": 1}
for i in dict1:
    print(i)
# 访问字典的键值对:
dict1 = {"name": "小明", "birth": "2005/06", "code": 1}
for i, j in dict1.items():
    print("key = ", i, ", value = ", j)

输出

name
birth
code
key =  name , value =  小明
key =  birth , value =  2005/06
key =  code , value =  1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太阳的影子wing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值