Python基础-迭代Iteration

来源:互联网 发布:怎么把淘宝小号养到2心 编辑:程序博客网 时间:2024/06/06 02:32

迭代

遍历出list、turple、dict等里面的每一个元素。

迭代List

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# 迭代ListmList = ["李雷","韩梅梅"]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 -*-# 迭代TurplemTurple = ("李雷","韩梅梅")for intem in mTurple:    print("迭代Turple",intem)

运行结果

D:\PythonProject>python Run.py迭代Turple 李雷迭代Turple 韩梅梅

迭代Dict

示例

#!/usr/bin/env python3# -*- coding: utf-8 -*-# 迭代DictmDict = {'李雷': 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 Iterableresult = isinstance("abc", Iterable)print(result)

运行结果

D:\PythonProject>python Run.pyTrue

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