mirror of https://github.com/TwoWater/Python
62 lines
1.4 KiB
Markdown
62 lines
1.4 KiB
Markdown
# 一、迭代 #
|
||
|
||
什么叫做迭代?
|
||
|
||
比如在 Java 中,我们通过 List 集合的下标来遍历 List 集合中的元素,在 Python 中,给定一个 list 或 tuple,我们可以通过 for 循环来遍历这个 list 或 tuple ,这种遍历就是迭代。
|
||
|
||
可是,Python 的 `for` 循环抽象程度要高于 Java 的 `for` 循环的,为什么这么说呢?因为 Python 的 `for` 循环不仅可以用在 list 或tuple 上,还可以作用在其他可迭代对象上。也就是说,只要是可迭代的对象,无论有没有下标,都是可以迭代的。
|
||
|
||
比如:
|
||
|
||
```python
|
||
|
||
# -*- coding: UTF-8 -*-
|
||
|
||
# 1、for 循环迭代字符串
|
||
for char in 'liangdianshui' :
|
||
print ( char , end = ' ' )
|
||
|
||
print('\n')
|
||
|
||
# 2、for 循环迭代 list
|
||
list1 = [1,2,3,4,5]
|
||
for num1 in list1 :
|
||
print ( num1 , end = ' ' )
|
||
|
||
print('\n')
|
||
|
||
# 3、for 循环也可以迭代 dict (字典)
|
||
dict1 = {'name':'两点水','age':'23','sex':'男'}
|
||
|
||
for key in dict1 : # 迭代 dict 中的 key
|
||
print ( key , end = ' ' )
|
||
|
||
print('\n')
|
||
|
||
for value in dict1.values() : # 迭代 dict 中的 value
|
||
print ( value , end = ' ' )
|
||
|
||
print ('\n')
|
||
|
||
# 如果 list 里面一个元素有两个变量,也是很容易迭代的
|
||
for x , y in [ (1,'a') , (2,'b') , (3,'c') ] :
|
||
print ( x , y )
|
||
|
||
```
|
||
|
||
输出的结果如下:
|
||
|
||
```txt
|
||
l i a n g d i a n s h u i
|
||
|
||
1 2 3 4 5
|
||
|
||
name age sex
|
||
|
||
两点水 23 男
|
||
|
||
1 a
|
||
2 b
|
||
3 c
|
||
```
|