在这个练习中用一个 for-loop 来创建和打印各种列表。
在能够用一个 for-loop 之前,需要一种方法来把这些循环的结果储存在某处。最好的办法就是用列表。
列表顾名思义就是一个按顺序从头到尾组成的某种东西的容器。它并不复杂:你只需要学习一个新的语法。
首先,你可以这样创建列表:
hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green'] weights = [1, 2, 3, 4]
以左方括号( [ )开始打开列表,然后把你想要的条目用逗号隔开放进去,有点类似于函数的参数。最后,用右方括号( ] )来表明列表的结束。Python 会选取这个列表以及它的所有内容并把它们分配到变
量里。
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 throuth a list
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
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
for i in range(0, 6):
print(f"Adding {i} to the list.")
# append is a function that lists understand
elements.append(i)#append() 方法用于在列表末尾添加新的对象。
#now we can print them out too
for i in elements:
print(f"Element was: {i}")
'''-----------------------------------------------------------------------------'''
'''
1. 看看你是如何使用 range 的。查阅上面的 range 函数并理解掌握。
range() 函数可创建一个整数列表,一般用在 for 循环中。
range(start, stop[, step])
2. 你能在第 22 行不使用 for-loop,而是直接把 range(0, 6) 赋给 elements 吗?
3. 找到 Python 文档关于列表的部分,然后读一读。看看除了 append,你还能对列表做哪些操作?
'''
如何创建一个二维列表?
可以用这种列表中的列表: [[1,2,3],[4,5,6]]
列表(lists)和数组(arrays)难道不是一个东西吗?
这取决于语言以及实现方法。在传统术语中,列表和数组的实现方式不同。在 Ruby 中都叫做 arrays,在 python 中都叫做 lists。所以我们就把这些叫做列表吧。
为什么 for-loop 可以用一个没有被定义的变量?
变量在 for-loop 开始的时候就被定义了,它被初始化到了每一次 loop 迭代时的当前元素中。
为什么 range(1, 3) 中的 i 只循环了两次而不是三次?
range() 函数只处理从第一个到最后一个数,但不包括最后一个数,所以它在 2 就结束了。这是这类循环的通用做法。
element.append() 的作用是什么?
它只是把东西追加到列表的末尾。打开 Python shell 然后创建一个新列表。任何时候当你遇到类似的用法,试着多玩几次,去体会它们的作用。