python 如何遍历

原创
admin 13小时前 阅读数 3 #Python

Python中的遍历方法

Python中遍历列表、元组和字典等可迭代对象是非常常见的操作,下面将介绍Python中常见的遍历方法。

使用for循环遍历列表

使用for循环可以遍历列表中的每个元素,并将其存储在变量中。

my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)

输出结果为:

1
2
3
4
5

使用while循环遍历列表

除了使用for循环外,还可以使用while循环遍历列表。

my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
    print(my_list[i])
    i += 1

输出结果为:

1
2
3
4
5

遍历字典

除了遍历列表外,还可以使用for循环遍历字典中的键值对。

my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
    print(f"{key}: {value}")

输出结果为:

a: 1
b: 2
c: 3

四、使用in关键字检查元素是否在可迭代对象中存在

使用in关键字可以检查一个元素是否在给定的可迭代对象中存在。

my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print("3 exists in the list")
else:
    print("3 does not exist in the list")

输出结果为:

上一篇:python如何学好 下一篇:python如何录音
热门