Python基础-迭代Iteration

xiaoxiao2021-02-28  5

迭代

迭代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