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

98 阅读1分钟

@TOC

一、数据结构的遍历

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