在Python中,`for`循环用于遍历序列(如列表、组、字典、字符串等)或其他可迭代对象。以下是使用`for`循环遍历的一些基本方法:
遍历列表
```python
方法1:使用for循环简单结构遍历
cities = ["Guangzhou", "Beijing", "Shanghai", "Nanjing"]
for city in cities:
print(city)
方法2:使用range()和len()函数遍历
for i in range(len(cities)):
print(i+1, cities[i])
方法3:使用enumerate()函数遍历
for i, city in enumerate(cities):
print(i+1, city)
遍历字符串
```python
string = "Hello World"
for char in string:
print(char)
遍历字典
```python
遍历字典的键
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
for key in my_dict:
print(key, my_dict[key])
遍历字典的键值对
for key, value in my_dict.items():
print(key, value)
遍历组
```python
t = (1, 2, 3)
for item in t:
print(item)
遍历字典的键值对(按字母顺序)
```python
my_dict = {"Name": "Zara", "Age": 7, "Class": "First", "Address": "Beijing"}
for key in sorted(my_dict):
print(key, ":", my_dict[key])
遍历多个序列
```python
x = [1899, 1900, 1901, 2000, 2099, 2100, 2101]
y = [0, 1, 2, 6, 11, 12, 13]
z = [0, 1, 2, 15, 30, 31, 32]
for a in range(len(x)):
for b in range(len(y)):
for c in range(len(z)):
print(x[a], y[b], z[c])
遍历列表搜索指定姓名
```python
students = [{"name": "关羽", "age": 18}, {"name": "张飞", "age": 23}, {"name": "刘备", "age": 21}, {"name": "曹操", "age": 35}]
find_name = input("请输入姓名:")
for student in students:
if student["name"] == find_name:
print("您输入的是:", student)
break
以上示例展示了如何使用`for`循环遍历不同类型的数据结构。您可以根据实际需求选择合适的方法进行遍历操作
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/8065.html