Python中的列表List

以下只是个人在学习中摘抄的一些知识点,便于自己的理解与对语言的掌握。

1.函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是 传值调用 (这里的  总是一个对象引用,而不是该对象的值)。 一个函数被另一个函数调用时,一个新的局部符号表在调用过程中被创建。

 

2.关于插入list的a[len(a):] = [y]方法。

  使用append(可以是list也可以是字符串)追加方法把一个值插入一个列表比使用+运算符(list1 = list1 + list2)更快

>>> a = ['asd', '748', 'zxc', 123, 465, 1.3] 
>>> x = 'add'
>>> y = 'add2'
>>> a.append(x)
>>> a
['asd', '748', 'zxc', 123, 465, 1.3, 'add']
>>> a[len(a):] = [y] 
>>> a
['asd', '748', 'zxc', 123, 465, 1.3, 'add', 'add2']

和此相同的还有一大类,见python参考手册

http://www.pythondoc.com/pythontutorial27/datastructures.html#tut-loopidioms

extend()方法

  extend()方法和append()方法非常类似,append()是把传给他的值整个加入到列表的末尾

  而extend()方法会把传给他的值打散在一项一项的插入到列表末尾。

>>> list1 = [1, 2, 3] 
>>> list1
[1, 2, 3]
>>> list1.append(['dasd', 'qeew', '4656']); list1
[1, 2, 3, ['dasd', 'qeew', '4656']]
>>> list1.extend(['dasd', 'qeew', '4656']); list1 
[1, 2, 3, ['dasd', 'qeew', '4656'], 'dasd', 'qeew', '4656']
>>>

 

 

3.删除并以弹出的形式返回元素。

list.pop([i])

如果没有指定索引,a.pop() 返回最后一个元素。元素随即从链表中被删除。

(方法中 i 两边的方括号表示这个参数是可选的,而不是要求你输入一对方括号,你会经常在 Python 库参考手册中遇到这样的标记。)

 

4.list的sort方法

sort(iterable[, cmp[, key[, reverse]]])

注意,[]表示相关参数是可选的

 

列表的sort()方法是需要传递一个列表值,返回其按字母表顺序或者数字顺序重新排序过后的列表

但是,请注意,sort()是有可选参数key 和 reverse的

使用key参数了就等于你希望按照特定某个项的顺序来进行排序    它可能是字母或者数字

使用reverse参数就是默认顺序或者他的反序

>>> mylist1 = 7589955
>>> mylist2 = [465, 798, 1, 2, 32] 
>>> mylist3 = ['A', 'B', 'D', 'C'] 
>>> mylist4 = ABDC                
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ABDC' is not defined
>>> mylist4 = 'ABDC'
>>> mylist1.sort()  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'sort'
>>> mylist2.sort() 
>>> mylist2
[1, 2, 32, 465, 798]
>>> mylist3.sort(); mylist3
['A', 'B', 'C', 'D']
>>> mylist4.sort(); mylist4 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'sort'
>>> mylist3.sort(reverse = True); mylist3 
['D', 'C', 'B', 'A']

key关键字也可以接受一个函数,那么这个sort就会在调用时给一个值,

按照把这个值传给那个函数得到的返回值的字母表或者数字顺序来排序

 

 

 

5.堆栈,堆栈是特定的数据结构,特点是先进后出,python可以轻易的实现:

使用list.append(x)来添加元素到堆栈顶

使用list.pop()将堆栈顶的元素弹出

 

6.队列也是特殊的数据结构,特点是先进先出,Python中也是可以实现,但是相比于末尾弹出,列表头插入和弹出是不‘不经济的’,

因为相对来说从列表末尾添加和弹出很快;在头部插入和弹出很慢(因为为了一个元素,要移动整个列表中的所有元素)。

Python专门设计了一种在列表头快速弹出的方法:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

插入就比较简单了:例如 a.insert(0, x) 会插入到整个链表之前

 

7.函数式编程工具, filter(),map() 以及 reduce()

filter(function, sequence) 返回一个 sequence(序列),包括了给定序列中所有调用 function(item) 后返回值为 true 的元素(如果可能的话,会返回相同的类型)。

如果该 序列 (sequence)是一个 strunicode 或者 tuple,返回值必定是同一类型,否则,它总是 list。例如,以下程序可以计算一个被 3 或者 5 整除的序列:

>>> def f(x):return x % 3 == 0 or x % 5 == 0
... 
>>> filter(f,range(2,100)) 
<filter object at 0x00E761C0>
>>> filter(f, range(2, 25)) 
<filter object at 0x00E761D8>
>>> print(f)               
<function f at 0x00E99460>
>>> print(filter(f,range(2,100)))  
<filter object at 0x00E76250>
>>> print(list(filter(f,range(2,100)))) 
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99]

出现<filter object at 0x00E761C0>是因为filter返回一个列表需要list()帮助。

 

map(function, sequence) 为每一个元素依次调用 function(item) 并将返回值组成一个链表返回。

可以传入多个序列,函数也必须要有对应数量的参数,执行时会依次用各序列上对应的元素来调用函数

>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]

 

reduce(function, sequence) 返回一个单值,它是这样构造的:首先以序列的前两个元素调用函数 function,再以返回值和第三个参数调用,依次执行下去。

如果序列中只有一个元素,就返回它,如果序列是空的,就抛出一个异常。

可以传入第三个参数作为初始值。如果序列是空的,就返回初始值,否则函数会先接收初始值和序列的第一个元素,然后是返回值和下一个元素,依此类推。

 

8.创建列表

  • 从序列中,使用列表推导式:列表推导式由包含一个表达式的括号组成,表达式后面跟随一个 for 子句,之后【可以有零或多个 for或 if 子句】。结果是一个列表,由表达式依据其后面的 for 和 if 子句上下文计算而来的结果构成。
>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> str = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
>>> str
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

  如果想要得到一个元组 (例如,上面例子中的 (x, y)),必须要加上括号:

>>> str2 = [(x, x**2) for x in range(6)]                                    
>>> str2
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> str2 = [x, x**2 for x in range(6)]   
  File "<stdin>", line 1
    str2 = [x, x**2 for x in range(6)]
                    ^
SyntaxError: invalid syntax
>>>

  列表推导式可嵌套函数,也可以使用复杂的表达式:

 9.创建集合set

  集合是Python中的一种特殊数据结构。集合的特点是无序、不重复,基本功能包括关系测试和消除重复元素。集合对象还支持 union(联合),intersection(交),difference(差)和 sysmmetric difference(对称差集)等数学运算。

注意:想要创建空集合,你必须使用 set() 而不是 {}。{}用来创建空字典。

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit                 # fast membership testing
True
>>> 'crabgrass' in fruit
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b                              # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                              # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                              # letters in both a and b
set(['a', 'c'])
>>> a ^ b                              # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

类似于列表推导式,也有集合推导式用法:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

 

posted @ 2020-08-10 20:06  PiaYie  阅读(175)  评论(0编辑  收藏  举报