python for的用法

python for的用法


2024年5月22日发(作者:)

python for的用法

Python中for的用法非常灵活,可以用来遍历列表、元组、字

符串、字典等数据类型,也可以用来生成数列、迭代器等。

1. 遍历列表、元组、字符串

可以使用for循环遍历列表、元组、字符串等序列类型的数据。

例如:

```python

fruits = ['apple', 'banana', 'orange']

for fruit in fruits:

print(fruit)

# 输出结果为:

# apple

# banana

# orange

```

2. 遍历字典

可以使用for循环遍历字典,遍历的是字典的键。例如:

```python

scores = {'Alice': 80, 'Bob': 90, 'Charlie': 85}

for name in scores:

print(name, scores[name])

# 输出结果为:

- 1 -

# Alice 80

# Bob 90

# Charlie 85

```

如果需要遍历字典的值,可以使用字典的values()方法:

```python

scores = {'Alice': 80, 'Bob': 90, 'Charlie': 85}

for score in ():

print(score)

# 输出结果为:

# 80

# 90

# 85

```

如果需要遍历字典的键值对,可以使用字典的items()方法:

```python

scores = {'Alice': 80, 'Bob': 90, 'Charlie': 85}

for name, score in ():

print(name, score)

# 输出结果为:

# Alice 80

# Bob 90

- 2 -

# Charlie 85

```

3. 生成数列

可以使用for循环生成数列,例如:

```python

for i in range(1, 10):

print(i)

# 输出结果为:

# 1

# 2

# 3

# 4

# 5

# 6

# 7

# 8

# 9

```

4. 迭代器

可以使用for循环遍历迭代器对象,例如:

```python

class MyIterator:

- 3 -

def __init__(self, n):

self.n = n

self.i = 0

def __iter__(self):

return self

def __next__(self):

if self.i < self.n:

i = self.i

self.i += 1

return i

else:

raise StopIteration()

my_iterator = MyIterator(5)

for i in my_iterator:

print(i)

# 输出结果为:

# 0

# 1

# 2

# 3

- 4 -

# 4

```

以上就是for在Python中的常见用法。

- 5 -


发布者:admin,转转请注明出处:http://www.yc00.com/news/1716326001a2727314.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信