笨方法学python
习题32
循环和列表:
#创建列表
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'orranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list:
#第一种for循环遍历列表
for number in the_count:
print(f"This is count {number}")
# same as above:
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# also we can go through mixed lists too:我们也可以浏览混合列表
# notice we have to use {} since we don't know what's in it:
# 注意我们必须使用{},因为我们不知道其中包含什么
#i和j都是短变量,可替代例表中的内容
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
#我们也可以建立清单,首先从一个空的清单开始
elements = []
# then use the range function to do 0 to 5 counts:
#然后使用范围功能进行0到5个计数
# range访问固定数值范围,即range(0, 6)就是0,1,2,3,4,5
for i in range(0, 6):
print(f"Adding {i} to the list.")
#append is a function that lists understand:
#append是一个列表理解的功能
elements.append(i)
print(">>> elements=",elements)
# now we can print them out too:
# 现在我们也可以将它们打印出来
for i in elements:
print(f"Elements was: {i}")
print("<<< exit elements")
运行结果:
1.注意一下range的用法。查一下range函数并理解它。
python range()函数可以创建一个整数列表,一般用在for循环中,range访问固定数值范围,即range(0, 6)就是0,1,2,3,4,5。
2.在第22行,可以直接将elements 赋值为range(0, 6),而无须使用for循环吗?
不可以。
如何创建二位列表?
就是在列表中包含列表,如[ [1, 2, 3], [4, 5, 6] ]。
为什么for循环可以使用未定义的变量?
for循环开始时这个变量就被定义了,每次循环碰到他的时候,它都会被重新初始化为当前循环中的元素值。
为什么for i in range(1, 3):只循环2次而非3次?
range()函数会从第一个数数到最后一个数,但不包含最后一个数。所以。它到2的时候就停止了,而不会到3。这种含首不含尾的方式是循环中极其常见的一种用法。
elements.append()是做什么的?
它的功能是在列表的尾部追加元素。打开 Python 命令行,创建几个列表试验一下,以后每次遇到自己不明白的东西,你都可以在 Python shell 交互模式试验一下。