day 3 list列表生成式
Posted 不要被骄傲遮蔽了双眼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day 3 list列表生成式相关的知识,希望对你有一定的参考价值。
1.定义一个list列表,里面元素是0-33
a = [] i = 0 while i<33: a.append(i) i+=1 print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
2.range (切片)
1)python2 版本
range风险:python2 版本中,有时候一次性申请很大的内存,不会给你
#### range 返回list列表 和切片功能相同 In [1]: range(10) Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [2]: range(10,17) Out[2]: [10, 11, 12, 13, 14, 15, 16] In [3]: range(10,17,2) Out[3]: [10, 12, 14, 16]
In [5]: range(0,100000) ### 运行结果 994, 995, 996, 997, 998, 999, ...]
In [5]: range(0,1000000000) --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) <ipython-input-5-30124a0b9388> in <module>() ----> 1 range(0,1000000000) MemoryError: ##range风险:python2 版本中,有时候一次性申请很大的内存,不会给你
2)python3版本:要一个数字,给你一个,不会全部一次性给
In [1]: range(0,10) Out[1]: range(0, 10) In [2]: range(10) Out[2]: range(0, 10) In [3]: range(0,100000000) Out[3]: range(0, 100000000)
3.列表生成式
1) a = [ i for i in range(0,18) ]
In [6]: a = [i for i in range(0,18)] In [7]: a Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] In [8]: a = [22 for i in range(0,18)] #for只负责循环的次数17次 In [9]: a Out[9]: [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22]
2) a = [ i for i in range(10) if i%2==0 ]
In [10]: a = [i for i in range(10) if i%2==0] In [11]: a Out[11]: [0, 2, 4, 6, 8]
3) d = [ (i,j) for i in range(3) for j in range(2)]
In [15]: d = [ i for i in range(3) for j in range(2)] In [16]: d Out[16]: [0, 0, 1, 1, 2, 2] In [17]: d = [ i,j for i in range(3) for j in range(2)] File "<ipython-input-17-0277977bdeb0>", line 1 d = [ i,j for i in range(3) for j in range(2)] ^ SyntaxError: invalid syntax
In [19]: d = [ (i,j) for i in range(3) for j in range(2)] In [20]: d Out[20]: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] #坐标轴
4)e = [(i,j,k) for i in range(3) for j in range(2) for k in range(2)]
In [21]: e = [(i,j,k) for i in range(3) for j in range(2) for k in range(2)] In [22]: e Out[22]: [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (2, 0, 0), (2, 0, 1), (2, 1, 0), (2, 1, 1)]
以上是关于day 3 list列表生成式的主要内容,如果未能解决你的问题,请参考以下文章