1.list
声明一个list很简单,只需list1=[](尽量不要将变量名起为关键字list)。
list有如下基本方法:
(1)append(x) 在list的末尾添加一个元素x,并且返回None
list1 = [1, 2, 3, 4]
r = list1.append(5)
print(list1, r)
#[1, 2, 3, 4, 5] None
(2)extend(iterable) 将另一个iterable的对象添加到list尾部,返回值为None。
list1 = [1, 2, 3, 4]
r = list1.extend([5, 6, 7, 8])
print(list1, r)
#[1, 2, 3, 4, 5, 6, 7, 8] None
(3)insert(i,x) 将元素x插入到索引i处,返回值为None。
list1 = [1, 2, 3, 4]
r = list1.insert(4, 5)
print(list1, r)
#[1, 2, 3, 4, 5] None
(4)remove(x) 删除值为x的元素(值而非索引),删除成功返回None,若没有x则报错
list1 = [1, 2, 3, 4]
r = list1.remove(3)
print(list1, r)
#[1, 2, 4] None
list1 = [1, 2, 3, 4]
r = list1.remove(5)
print(list1, r)
Traceback (most recent call last):
File "E:/Programs/python/data-structure/list-demo.py", line 2, in <module>
r = list1.remove(5)
ValueError: list.remove(x): x not in list
(5)pop([i]) 如果传入参数i,删除索引i处元素。如果不传参,删除尾部的元素。返回值为删掉的元素。
list1 = [1, 2, 3, 4]
r = list1.pop(3)
print(list1,r)
#[1, 2, 3] 4
(6)clear() 清空数组所有元素,返回None。相当于list1[:]=[]以及del list1[:]
list1 = [1, 2, 3, 4]
r = list1.clear()
print(list1, r)
#[] None
(7)count(x) 返回x在list中出现的次数
list1 = [1, 2, 3, 4, 1, 2, 3, 4, 2, 4]
r = list1.count(4)
print(r)
#3
(8)sort(key=None, reverse=False) 默认从小到大,如果reverse设为True则为从大到小。key为一个lambda表达式,传入当前元素,返回sort时依据德关键字。
list1 = [{'age': 20}, {'age': 15}, {'age': 18}, {'age': 25}]
list1.sort(key=lambda stu: stu['age'])
print(list1)
(9)reverse() 反转数组
list1 = [1, 2, 3, 4, 5]
list1.reverse()
print(list1)
#[5, 4, 3, 2, 1]
(10)copy() 浅拷贝数组,相当于list1[:]
list1 = [1, 2, 3, 4, {'name': 'John'}]
list2 = list1.copy()
list2[4]['name'] = 'Mike'
print(list1 is list2)
print(list1)
print(list2)
#
False
[1, 2, 3, 4, {'name': 'Mike'}]
[1, 2, 3, 4, {'name': 'Mike'}]
以上为list常用方法。
list可以作为栈使用。
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
(官网代码)
也可以作为队列使用,但是需要导入collections包的deque
>>> 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'])
初始化list的小窍门:
list1 = [x ** 2 for x in range(10)]
print(list1)
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [num for sub in list1 for num in sub]
print(list1)
print(list2)
#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
list1 = [(x, y) for x in range(1, 4) for y in range(x, 4)]
print(list1)
#[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
matrix = [[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]
r = [[row[i] for row in matrix] for i in range(4)]
print(r)
#[[1, 5, 9], [2, 6, 10], [4, 7, 11], [5, 8, 12]](官网案例)
del语句:del arr[i]删除索引为i的元素,del arr[:]为清空数组,del arr[i:j]为清空i到j之前的元素,包括i不包括j。
遍历方式
list1 = [1, 2, 3, 4, 5, 6, 7, 8]
for i in range(len(list1)):
print(i, list1[i])
for i, val in enumerate(list1):
print(i, val)
2.tuple
tuple1 = () 此时tuple1为tuple类型
tuple2 = (1) 此时tuple2非tuple类型,而是int类型
tuple3 = 1, 或者 tuple3 = (1,) 此时tuple3为tuple类型
tuple1 = ()
tuple2 = (1)
tuple3 = 1,
tuple4 = 1, 2, 3, 4
tuple5 = tuple4, 5
print(type(tuple1))
print(type(tuple2))
print(type(tuple3))
print(type(tuple4))
print(tuple5)
#<class 'tuple'>
<class 'int'>
<class 'tuple'>
<class 'tuple'>
((1, 2, 3, 4), 5)
tuple可以使用切片,但是tuple不可变,不能给其中元素重新赋值。
tuple1 = 1, 2, 3, 4, 5, 6
tuple1[2] = 5
#Traceback (most recent call last):
File "E:/Programs/python/data-structure/list-demo.py", line 2, in <module>
tuple1[2] = 5
TypeError: 'tuple' object does not support item assignment
可以通过以下代码实现两个变量值的互换
x = 5
y = 6
x, y = y, x
print(x)
print(y)
#6
5
3.set
执行set1={}这种语句,set1的类型为dict而非set
set1 = {}
print(type(set1))
#<class 'dict'>
当用set构造函数创建set时要注意以下的问题:
set1 = set('abcedfg')
print(set1)
#{'f', 'c', 'g', 'e', 'b', 'a', 'd'}
set是无序的,并且其中没有重复元素,因此可以通过set实现去重。
list1 = [1, 1, 2, 3, 4, 4, 5, 6, 6, 7]
print(list(set(list1)))
#[1, 2, 3, 4, 5, 6, 7]
set可以进行求交集,并集,差集,以及找出只存在于其中一个的元素集合
a = set('abracadabra')
b = set('alacazam')
print(a)
print(b)
print(a & b)
print(a | b)
print(a - b)
print(a ^ b)
#
{'r', 'b', 'a', 'c', 'd'}
{'z', 'a', 'm', 'c', 'l'}
{'c', 'a'}
{'z', 'r', 'b', 'a', 'm', 'c', 'd', 'l'}
{'r', 'b', 'd'}
{'z', 'm', 'r', 'b', 'd', 'l'}
4.dict
初始化dict,需要将key与value都加上引号:
dict1 = {'name': 'Jero', 'age': 20}
获取可采用更简单的方法
dict2 = dict(name='Jero', age=20)
遍历dict时,有如下选择
dict1 = {'name': 'Jero', 'age': 20, 'gender': 'male'}
for i in dict1:
print(i, dict1[i])
#name Jero
age 20
gender male
for val in dict1.values():
print(val)
#Jero
20
male
for key, val in dict1.items():
print(key, val)
运算:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 * 2)
list1 += list2
print(list1)
#[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。