可迭代对象

Python 包含以下几种可迭代对象:

  1. 序列. 包含: 字符串, 列表, 元组

  2. 字典

  3. 迭代器对象 ( iterator )

  4. 生成器函数 ( generator )

  5. 文件对象

我们已经在前面学习了序列, 字典等知识, 迭代器对象和生成器函数将在后面进行详解. 接下来, 我们通过循环来遍历这几种类型的数据:

注意:range( start, stop, step) 是生成一个迭代器的函数

for 循环遍历可迭代对象

for 循环通常用于可迭代对象的遍历.

for 循环的语法如下:

for  变量名  in 可迭代对象:
		循环体语句
  1. 遍历字符串中的字符
for letter in 'Python':     # 第一个实例
    print ('当前字母 :', letter)

显示结果:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
  1. 遍历列表
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
    print ('当前水果 :', fruit)

显示结果:

当前水果 : banana
当前水果 : apple
当前水果 : mango
  1. 遍历字典
d = {"name":"我是小白", "age":18, "address":"中国"}

print('遍历字典d: ')
for x in d:              #遍历字典所有的 key 
    print(x)
    
print('遍历字典所有的 key ')
for x in d.keys():    #遍历字典所有的 key
    print(x)
    
print('#遍历字典所有的 value: ')
for x in d.values():  #遍历字典所有的 value
    print(x)
    
print('遍历字典所有的 "键值对": ')
for x in d.items():     #遍历字典所有的 "键值对",以元组的形式输出
    print(x)

显示结果:

遍历字典d: 
name
age
address
遍历字典所有的 key 
name
age
address
#遍历字典所有的 value: 
我是小白
18
中国
遍历字典所有的 "键值对": 
('name', '我是小白')
('age', 18)
('address', '中国')

range 对象

range 对象是一个迭代器对象, 用来产生指定范围的数字序列. 格式为:

range(start, end, step)

生成的数值序列从 start 开始到 end 结束 (不包含 end). 若没有填写 start, 则默认从 0 开始. step 是可选 的步长, 默认为1

如下是几种典型示例:

for i in range(10) 产生序列: 0 1 2 3 4 5 6 7 8 9
for i in range(3,10) 产生序列: 3 4 5 6 7 8 9
for i in range(3,10,2) 产生序列: 3 5 7 9

注意:range()函数在python2和python3中有较大变化;
在python2中,直接使用range函数输出的是序列;但是在python3中不会输出序列,采用惰性方式,仅在遍历使用时才提供内容,这样较好的节约了内存

x = range(3,10)
print(x)
print(type(x))

显示效果:

range(3, 10)
<class 'range'>

range在循环中的使用:

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
    print('当前水果 :', fruits[index])

显示效果:

当前水果 : banana
当前水果 : apple
当前水果 : mango
for _ in range () 中‘_‘的意思

python 中 for _ in range () 中’_'的意思

以斐波那契数列为例

#求前20项的斐波那契数
a = 0
b = 1
for _ in range(20):
    (a, b) = (b, a + b)
    print(a, end=' ')

其中’_’ 是一个循环标志,也可以用i,j 等其他字母代替,下面的循环中不会用到,起到的是循环此数的作用
就像C语言中

for (int i ; i<100 ; i++){
    代码块;
}

其中的 ’i’ 在下面并不会用到,起到的只是控制循环此数的作用

嵌套循环

一个循环体内可以嵌套另一个循环, 一般称为 “嵌套循环”, 或者 “多重循环”.

for num in range(10,20):  # 迭代 10 到 20 之间的数字
    for i in range(2,num): # 根据因子迭代
        if num%i == 0:      # 确定第一个因子
            j=num/i          # 计算第二个因子
            print ('%d 等于 %d * %d' % (num,i,j))
        break            # 跳出当前循环
    else:                  # 循环的 else 部分
        print (num, '是一个质数')

显示效果:

10 等于 2 * 5
12 等于 2 * 6
14 等于 2 * 7
16 等于 2 * 8
18 等于 2 * 9

break 与 continue 语句

  • break 语句

break 语句可用于 while 和 for 循环, 用来结束整个循环. 当有嵌套循环时, break 语句只能跳出最近一层的循环.

  • continue 语句

countinue 语句用于结束本次循环, 继续下一次. 多个循环嵌套时, countinue 也是应用最近的一层循环.

for i in range(0,10):
    if (i%2 == 0):
        continue
    else :
        print(i)

循环中 else 语句的特殊用法

while, for 循环可以附带一个 else 语句 ( 可选 ). 如果 for, while 语句没有被 break 语句结束, 则会执行 else 子句, 否则不执行. 语法格式如下:

while  条件表达式:
    循环体 
else:
    语句块

或者:

for 变量 in 可迭代对象:
    循环体 
else:
    语句块
count = 0
while count < 5:
    print (count, " is  less than 5")
    count = count + 1
else:
    print (count, " is not less than 5")

显示效果:

0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5

使用 zip() 并行迭代

我们可以通过 zip() 函数对多个序列进行并列进行并行迭代, zip() 函数在最短序列 “用完” 时就会停止.

names = ("Alice", "Bob", "Kiff")
ages = (10, 12)
jobs = ("小学生", "中学生", "大学生","研究生")

print(list(zip(names, ages, jobs)))

for name, age, job in zip(names, ages, jobs):
    print("{0}--{1}--{2}".format(name, age, job))

运行结果:

[('Alice', 10, '小学生'), ('Bob', 12, '中学生')]
Alice--10--小学生
Bob--12--中学生
推导式创建序列

详见:https://blog.csdn.net/weixin_43848614/article/details/104918120

更多详解:
https://blog.csdn.net/weixin_43848614/article/details/104918120

https://blog.csdn.net/weixin_43848614/article/details/104920923

https://blog.csdn.net/zhuyin6553/article/details/90289879

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐