python学习总结(二)——操作列表

1、遍历整个列表

需要对列表中的每个元素都执行相同的操作时,可使用for循环

>>> colors
['green', 'orange', 'yellow', 'red']
>>> for color in colors:
	print(color)

	
green
orange
yellow
red

python先获取colors的第一个值‘green’,并储存到变量color中。
接下来打印color
python返回到循环的第一行
python获取列表下一个名字‘orange’,并储存到变量color中
然后继续打印
对于列表每个元素,都执行循环指定的步骤,且不管列表包含多少个元素

对于编写for程序的时候,对于用于储存你列表中每个值的变量,可指定任意名称。选择描述单个列表元素的有意义的名称大有帮助。比如cat-cats,dog-dogs,color-colors

2、for循环
colors = ['red','orange','yellow','green']
for color in colors:
	print("I like "+color+"!")
	print("But  i cannot like " +color+" all the time!\n")

print("Thank you")

运行结果:

I like red!
But  i cannot like red all the time!

I like orange!
But  i cannot like orange all the time!

I like yellow!
But  i cannot like yellow all the time!

I like green!
But  i cannot like green all the time!

Thank you

前两条print语句缩进会重复执行,第三条print语句没有缩进,因此只执行一次。

3、创建数字列表

range()函数
python从指定的第一个值开始到指定的倒数第二个值停止。
举个栗子:

for value in range(1,5):
	print(value)
1
2
3
4
for value in range(1,6):
1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值