码迷,mamicode.com
首页 > 其他好文 > 详细

day 3 list列表生成式

时间:2017-11-26 12:48:38      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:[1]   alt   inpu   --   pre   lis   bsp   分享   列表   

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列表生成式

标签:[1]   alt   inpu   --   pre   lis   bsp   分享   列表   

原文地址:http://www.cnblogs.com/venicid/p/7898595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!