数据类型的遍历

数据类型的遍历:for循环语句

  1. for循环用来遍历序列

  2. 通过不使用下标的方式来实现对序列中每一个元素的访问

  3. 遍历的对象:列表,元组,字符串,字典,集合

遍历列表

#遍历列表
a=[1,2,3,4,5]
for element in a:
    print(element,end=" ")
print()

#遍历列表的元素数据,同时输出元素对应的下标
for index,num in enumerate(a):
    print(index,num)
print()

遍历元组

#遍历元组
b=("a","b","c","d","e")
for element in b:
    print(element,end=" ")
print()

遍历字符串

c = "123abc"
for ch in c:
    print(ch, end=" ")      # 1 2 3 a b c
print()

遍历字典

先设置一个字典:

d = {
    "name": "联想笔记本",
    "price": 4800.00,
    "desc" : "值得信赖的笔记本",
    "sales": 1000
}

字典的各种遍历使用

# 方式一:输出字典的所有键值对
print(d.items())        # 字典的每一个键值对 dict_items([('name', '联想笔记本'), ('price', 4800.0), ('desc', '值得信赖的笔记本'), ('sales', 1000)])
for element in d.items():
    print(element[0], element[1], end=" ")  # name 联想笔记本 price 4800.0 desc 值得信赖的笔记本 sales 1000
print()


# 方式二:输出字典的所有键值对
for key in d.keys():
    print(key, d[key], end=" ") # name 联想笔记本 price 4800.0 desc 值得信赖的笔记本 sales 1000
print()


# 方式三:输出字典的所有键值对
for key, value in d.items():
    print(key, value, end=" ")
print()


# 方式四:循环输出字典的所有value值
for value in d.values():
    print(value, end=" ") # 联想笔记本 4800.0 值得信赖的笔记本 1000
print()


# 方式五:只会打印字典的 key
for key in d:
    print(key, end=" ")     # name price desc sales
print()

 

posted @ 2024-03-10 16:22  帅帅的编程之路  阅读(8)  评论(0编辑  收藏  举报