python for 第一次输出列表第一个 第二次输出列表第二个_python自学笔记操作列表3...

本文介绍了Python中for循环的基础用法,通过示例详细解释了如何遍历列表并执行不同操作,包括如何打印列表元素、执行多次操作,以及如何创建和使用数字列表。此外,还探讨了range()函数的使用,并展示了列表解析的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.方法for循环研究

循环是计算机自动完成重复工作的常见方式之一。

例如:

输入


magicians=['alice','davide','carolina']for magician in magicians:   print(magician)

输出


alicedavidecarolina

其中(for magician in magicians:)这行代码让python获取列表magicians中的第一个值('alice'),并将其存储到变量magician中。


 print(magician)

让python打印magician的值,依然是'alice'。因为其中还包含其他值,python返回到循环的第一行(for magician in magicians:)这行代码,python获取列表中的下一个名字‘davide’,将其存储到变量magician中,再次执行打印 print(magician)代码。

1.2在for循环中执行更多操作

在for循环中,可对每个元素执行任何操作,例如

输入


magicians=['alice','davide','carolina']for magician in magicians:    print(magician.title()+',that was a great trick!')    print("I can't wait to see your next trick, "+magician.title()+"." )

输出


Alice,that was a great trick!I can't wait to see your next trick, Alice.Davide,that was a great trick!I can't wait to see your next trick, Davide.Carolina,that was a great trick!I can't wait to see your next trick, Carolina.

在for循环中,想包含多少代码都可以。在代码(for magician in magicians:)后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。


如果忘记进行缩进,就会出现如下情况

magicians=['alice','davide','carolina']for magician in magicians:    print(magician.title()+',that was a great trick!')print("I can't wait to see your next trick, "+magician.title()+"." )#首行未进行缩进

输出

Alice,that was a great trick!Davide,that was a great trick!Carolina,that was a great trick!I can't wait to see your next trick, Carolina.

首行不缩进列表循环完毕,执行最后一次的值。打印出的结果就是如下。

(Carolina,that was a great trick!

I can't wait to see your next trick, Carolina.)


2.创建数字列表

列表非常适合用于存储数字集合,而python提供了很多工具,可帮助我们高效地处理数字列表。

2.1使用函数range()

输入

for value in range (1,5):    print(value)

输出

1234

在这个事例中,range()只是打印1~4,这是在编程语言中经常看到的差一行为的结果。函数range()让python从你指定的第一个数值开始,(我指定的第一个数字是1)并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为5).

2.2使用range()创建数字列表

要创建数字列表,可使用函数list(0将range()的结果直接转换为列表。如果将range()作为list()的参数,输出将为一个数字列表。

输入

number=list(range(1,6))print(number)ji_number=list(range(1,6,2))#从1开始加2print(ji_number)ou_number=list(range(2,6,2))#从2开始加2print(ou_number)

输出

[1, 2, 3, 4, 5][1, 3, 5][2, 4]

在这行代码中(ji_number=list(range(1,6,2))#从1开始加2)到6为止。

还可表示1~10的乘方运算

输入

squares=[]for value in range(1,11):    square=value**2    squares.append(square)#将suquare中循环值添加进入squares列表中print(squares)

输出

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2.3列表解析

输入

squares=[value**2 for value in range(1,11)]print(squares)

输出

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3bd2fa8e931d1b2e211586282366898c.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值