关于python中列表第三个参数问题

列表第三个参数的说明和使用示例,帮助理解的笔记

Posted by VK on June 1, 2020

关于python中列表第三个参数问题

当步长值小于0时,beg默认为len(array)-1,end默认为开头之前。

当 步长值大于0时,beg默认为0,end默认为最末之后。

>>> a=[1,2,3,4,5,6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a[0]=9
>>> a
[9, 2, 3, 4, 5, 6]
>>> a[1:3]=[8,9]
>>> a
[9, 8, 9, 4, 5, 6]
>>> a[1:3]=[]
>>> a
[9, 4, 5, 6]
>>> a[1:3:2]
[4]
>>> a
[9, 4, 5, 6]
>>> print(a[-4:])
[9, 4, 5, 6]
>>> print(a[-3:])
[4, 5, 6]
>>> print(a[:])
[9, 4, 5, 6]
>>> print(a[:-1])
[9, 4, 5]
>>> print(a[::-1])
[6, 5, 4, 9]
>>> a
[9, 4, 5, 6]
>>> print(a[-4::-1])
[9]
>>> print(a[::1])
[9, 4, 5, 6]
>>> print(a[::2])
[9, 5]
>>> print(a[::-2])
[6, 4]
>>> print(a[-2::-1])
[5, 4, 9]
>>> 

为了提高内存利用效率对于一些简单的对象,如一些数值较小的int对象,字符串对象等,python采取重用对象内存的办法.

    (1)如指向a=2,b=2时,由于2作为简单的int类型且数值小,python不会两次为其分配内存,而是只分配一次,然后将a与b同时指向已分配的对象。


a = 2
b = 2
print(id(a),id(b),id(2))
print('a == b:',a==b)
print('a is b:',a is b)
1683941872 1683941872 1683941872
a == b: True
a is b: True
e = 'test'
f = 'test'
print(id(e),id(f),id('test'))
print('e == f:',e==f)
print('e is f:',e is f)
2537402630528 2537402630528 2537402630528
e == f: True
e is f: True

     (2)如对于数值较大的int对象,python会为aa和bb分别申请一块内存,来存储1999839。

python 创建二维列表,将需要的参数写入 cols 和 rows 即可

list_2d = [[0 for col in range(cols)] for row in range(rows)]

实例:

>>> list_2d = [ [0 for i in range(5)] for i in range(5)]
>>> list_2d[0].append(3)
>>> list_2d[0].append(5)
>>> list_2d[2].append(7)
>>> list_2d
[[0, 0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 7], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]