Python基础-迭代Iteration

迭代

遍历出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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值