迭代
遍历出list、turple、dict等里面的每一个元素。
迭代List
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 迭代List
mList = ["李雷","韩梅梅"]
for intem in mList:
print("迭代List",intem)
for i, value in enumerate(mList):
print(i, value)
运行结果
D:\PythonProject>python Run.py
迭代List 李雷
迭代List 韩梅梅
0 李雷
1 韩梅梅
迭代Turple
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 迭代Turple
mTurple = ("李雷","韩梅梅")
for intem in mTurple:
print("迭代Turple",intem)
运行结果
D:\PythonProject>python Run.py
迭代Turple 李雷
迭代Turple 韩梅梅
迭代Dict
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 迭代Dict
mDict = {'李雷': 1, '韩梅梅': 2, 'c': 3}
for key in mDict:
print("迭代Dict key",key)
for mValue in mDict.values():
print("迭代Dict value",mValue)
for key,mValue in mDict.items():
print("迭代Dict",key, mValue)
运行结果
D:\PythonProject>python Run.py
迭代Dict key 李雷
迭代Dict key 韩梅梅
迭代Dict key c
迭代Dict value 1
迭代Dict value 2
迭代Dict value 3
迭代Dict 李雷 1
迭代Dict 韩梅梅 2
迭代Dict c 3
字符串迭代
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字符串迭代
mStr = "字符串迭代"
for mValue in mStr:
print(mStr,mValue)
运行结果
D:\PythonProject>python Run.py
字符串迭代 字
字符串迭代 符
字符串迭代 串
字符串迭代 迭
字符串迭代 代
判断是否可迭代
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 判断是否可以迭代
from collections import Iterable
result = isinstance("abc", Iterable)
print(result)
运行结果
D:\PythonProject>python Run.py
True
List套tuple迭代
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# List套tuple迭代
mList = [("李雷", "22岁"),("韩梅梅", "20岁")]
for name, age in mList:
print(name,age)
运行结果
D:\PythonProject>python Run.py
李雷 22岁
韩梅梅 20岁