🌰:往一个list中存入10~77这么多个元素。
#方法一:while循环♻️
In [1]: a = []
In [2]: i=10
In [3]: while i<=77:
...: a.append(i)
...: i+=1
...:
#方法二:for循环♻️
In [6]: a.clear()
In [10]: for i in range(10,78):
....: a.append(i)
....:
range() 方法:返回值是个列表
就是用来得到列表的。
mm@mm-virtual-machine:~$ ipython
In [1]: range(10) #默认从0开始
Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]: range(10,18) #包头不包尾
Out[2]: [10, 11, 12, 13, 14, 15, 16, 17]
In [3]: range(10,18,2) #步长2
Out[3]: [10, 12, 14, 16]
In [4]: range(1,10000000000)
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<ipython-input-4-25c39ba167d7> in <module>()
----> 1 range(1,10000000000)
MemoryError:
range()的风险:
1.你要了一个很大的空间,系统不给你,报异常。
2.你要了一个很大的空间,系统给你了,但是你忘了用,这个空间就一直占着。
这个风险在python3
中被克服了:
你什么时候问我要一个值,我什么时候现生成一个值给你。
mm@mm-virtual-machine:~$ ipython3
In [1]: range(10)
Out[1]: range(0, 10)
In [2]: range(10,18)
Out[2]: range(10, 18)
In [3]: range(1,10000000000)
Out[3]: range(1, 10000000000)
列表生成式:
for
循环只控制循环次数。
In [4]: a = [i for i in range(1,18)]
In [5]: a
Out[5]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
In [6]: b = [8 for i in range(1,18)]
In [7]: b
Out[7]: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
for
和if
一起用的时候:
In [8]: c = [i for i in range(10) if i%2==0]
In [9]: c
Out[9]: [0, 2, 4, 6, 8]
每执行一次外面的for
循环,都要执行两次里面的for
循环:
In [10]: d = [i for i in range(3) for j in range(2)]
In [11]: d
Out[11]: [0, 0, 1, 1, 2, 2]
In [12]: e = [(i,j) for i in range(3) for j in range(2)]
In [13]: e
Out[13]: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
三个for
循环的嵌套:
In [14]: f = [(i,j,k) for i in range(3) for j in range(2) for k in range(3)]
In [15]: f
Out[15]:
[(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(0, 1, 0),
(0, 1, 1),
(0, 1, 2),
(1, 0, 0),
(1, 0, 1),
(1, 0, 2),
(1, 1, 0),
(1, 1, 1),
(1, 1, 2),
(2, 0, 0),
(2, 0, 1),
(2, 0, 2),
(2, 1, 0),
(2, 1, 1),
(2, 1, 2)]