练习32--循环和列表

时间:2020-07-15 22:22:33   收藏:0   阅读:38

一 相关知识

1 range()函数

2 for循环

for iterating_var in sequence:
  statements(s)

3 append()方法

二 代码及执行结果

ex32.py文件

 1 the_count = [1,2,3,4,5]
 2 fruits = [apples,oranges,pears,apricots]
 3 changes = [1,pennies,2,dimes,3,quarters]
 4 
 5 # this first kind of for-loop goes through a list
 6 for number in the_count:
 7     print(f"This is count {number}")
 8 
 9 # same as above
10 for fruit in fruits:
11     print(f"A fruit of type:{fruit}")
12 
13 # also we can go through mixed lists too 
14 # notice we have to use {} since we don‘t know what‘s in it
15 for i in changes:
16     print(f"I got{i}")
17 
18 # we can also build lists,first start with an empty one
19 elements = []
20 
21 # then use the range function to do 0 to 5 counts
22 for i in range(0,6):
23     print(f"Adding {i} to the list.")
24     # append is a function that lists understand
25     elements.append(i)
26 
27 # now we can print them out too
28 for i in elements:
29     print(f"Element was: {i}")

执行结果:

PS E:\3_work\4_python\2_code_python\02_LearnPythonTheHardWay> python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type:apples
A fruit of type:oranges
A fruit of type:pears
A fruit of type:apricots
I got1
I gotpennies
I got2
I gotdimes
I got3
I gotquarters
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

三 一些问题

1、如何创建一个二维列表? 可以用这种列表中的列表: [[1,2,3],[4,5,6]]

2、列表(lists)和数组(arrays)难道不是一个东西吗? 这取决于语言以及实现方法。在传统术语中,列表和数组的实现方式不同。在 Ruby 中都叫做 arrays,在 python 中都叫做 lists。所以我们就把这些叫做列表吧。

3、为什么 for-loop可以用一个没有被定义的变量?变量在 for-loop 开始的时候就被定义了,它被初始化到了每一次 loop 迭代时的当前元素中。

 

原文:https://www.cnblogs.com/luoxun/p/13307180.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!