python 笔记 循环和列表 《笨办法学Python》习题32 ——1.6

习题 32: 循环和列表

目标与感悟:

• for-loop的使用,首先定义一个列表,list = [1, 2, 'dda'],之后定义变量位于列表,再进行打印等操作。

例:

list =[1,2,'dda']

for a inlist:

print"I got %r "%a


x.append(y)这个命令的作用是把y这个值所表达的内容添加到x的列表中。

假设先设置x列表=【】(空集)

那在运行x.append(y)命令之后x列表就会变成【y】

再次运行x.append(z)命令之后x列表就会变成【y,z】

 

for-loop可以直接使用range函数,pythonrange()函数会从第一个开始,但不包含最后一个数字,range也是一个列表。

ex32.py

#-*- coding:utf-8-*-
#此章的主题是for循环
 
 #[(左方括号)开头“打开”列表,然后写下你要放入列表的东西,用逗号隔开,就跟函数的参数一样,最后需要用  ]  (右方括号)结束右方括号的定义。
 
 
#此处就是定义一个列表,共定义了3个,按顺序将列表中数赋予给变量
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
 
# this first kind of for-loop goes through a list 
 
# for循环可以遍历任何序列的项目,如一个列表或者一个字符串。此处就是历遍the_count列表
for number in the_count:
	print "This is count %d" % number
# same as above
for fruit in fruits:
	print "A fruit of type: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
#%r能够打印python中原本的代码
for i in change:
	print "I got %r " %i
# we can also build lists, first start with an empty one
# 伏笔,此处定义一个新列表,列表为空
elements = []
 
# then use the range function to do 0 to 5 counts
# 此处可知python中range()函数会从第一个开始,但不包含最后一个数字
for i in range(0,6):
	print "Adding %d to the list." % i
	# append is a function that lists understand
	elements.append(i)
#x.append(y),作用是把y这个值所表达的内容添加到x的列表中。
 
# now we can print them out too
# 此时对elements列表的值进行验证
for i in elements:
	print "Element was: %d" % i

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值