Python基础-列表&元组&集合&字典

一、列表

在Python环境下,通过help命令查看list的方法

1
help([])
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#在列表末尾添加新的元素
| append(...)
| L.append(object) -> None -- append object to end
|
#清空列表所有元素
| clear(...)
| L.clear() -> None -- remove all items from L
|
#复制列表
| copy(...)
| L.copy() -> list -- a shallow copy of L
|
#统计某个元素在列表中出现的次数
| count(...)
| L.count(value) -> integer -- return number of occurrences of value
|
#在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
| extend(...)
| L.extend(iterable) -> None -- extend list by appending elements from the iterable
|
# 从列表中找出某个值第一个匹配项的索引位置
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
#将对象插入列表
| insert(...)
| L.insert(index, object) -- insert object before index
|
#移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
| pop(...)
| L.pop([index]) -> item -- remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
|
#移除列表中某个值的第一个匹配项
| remove(...)
| L.remove(value) -> None -- remove first occurrence of value.
| Raises ValueError if the value is not present.
|
#反向列表中元素
| reverse(...)
| L.reverse() -- reverse *IN PLACE*
|
#对原列表进行排序
| sort(...)
| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

注:列表方法多是直接作用在原列表上,不需要也不能赋值到新的变量

1
2
3
4
5
6
list1 = [2,3,1,6,9]
list2 = list1.sort()
print(list2)
--> None
print(list1)
--> [1,2,3,6,9]

常用函数

1
2
3
4
5
6
7
len(list) --> 列表元素个数

max(list) --> 返回列表元素最大值 非数字类型也可以

min(list) --> 返回列表元素最小值

del list[i] --> 删除列表中索引为i的元素

列表推导式

创建一个列表,列表中包含元素0-9的平方数,即[0,1,4,9,16,25,36,49,64,81]

1
2
3
4
5
6
7
#常规写法
s = []
for x in range(10):
s.append(x**2)

#列表推导式写法
s = [x**2 for x in range(10)]

列表推导式由包含一个表达式的中括号组成,表达式后跟随一个for子句,之后可以有0或多个for或if子句。

1
2
3
4
s = [(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]

#嵌套
z = [x + 1 for x in [x ** 2 for x in [1,2,3]]]

二、元组

元组是不可变类型,不能在元组内删除或添加或编辑任何值。元组的方法只有两个,用法与列表一致

1
2
3
4
5
|  count(...)
| T.count(value) -> integer -- return number of occurrences of value
|
| index(...)
| T.index(value, [start, [stop]]) -> integer -- return first index of value.

三、集合

集合是一个无序不重复元素的集,创建集合是会自动去重,并且随机排序

1
2
3
4
#使用set创建集合
a = set(abracadabra'')
print(a)
--> {'b', 'r', 'a', 'd', 'c'}
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#集合中增加元素
| add(...)
| Add an element to a set.
|
| This has no effect if the element is already present.

#清空集合所有元素
| clear(...)
| Remove all elements from this set.
|
#复制集合
| copy(...)
| Return a shallow copy of a set.
|
| difference(...)
| Return the difference of two or more sets as a new set.
|
| (i.e. all elements that are in this set but not the others.)
|
| difference_update(...)
| Remove all elements of another set from this set.
|
#删除集合中的指定元素,如果指定元素在集合中不存在则啥都不做
| discard(...)
| Remove an element from a set if it is a member.
|
| If the element is not a member, do nothing.
|
| intersection(...)
| Return the intersection of two sets as a new set.
|
| (i.e. all elements that are in both sets.)
|
| intersection_update(...)
| Update a set with the intersection of itself and another.
|
| isdisjoint(...)
| Return True if two sets have a null intersection.
|
| issubset(...)
| Report whether another set contains this set.
|
| issuperset(...)
| Report whether this set contains another set.
|
#随机删除一个元素,并返回删除的元素
| pop(...)
| Remove and return an arbitrary set element.
| Raises KeyError if the set is empty.
|
| remove(...)
| Remove an element from a set; it must be a member.
|
| If the element is not a member, raise a KeyError.
|
| symmetric_difference(...)
| Return the symmetric difference of two sets as a new set.
|
| (i.e. all elements that are in exactly one of the sets.)
|
| symmetric_difference_update(...)
| Update a set with the symmetric difference of itself and another.
|
| union(...)
| Return the union of sets as a new set.
|
| (i.e. all elements that are in either set.)
|
| update(...)
| Update a set with the union of itself and others.

集合运算

1
2
3
4
5
6
7
8
9
10
11
# a有而b没有的元素
a - b

#a有或b有的元素
a | b

#a有且b也有的元素
a & b

#a有或b有,但是又不同时存在的元素
a ^ b

四、字典

字典是无序的键值对(key:value)的集合,同一个字段内的键必须互不相同。

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|  clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D

#创建一个字典,字典的键来自iterable,value为None,不改变当前的字典
| fromkeys(iterable, value=None, /) from builtins.type
| Returns a new dict with keys from iterable and values equal to value.
|
#获取指定键的值
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
#返回可遍历的(键, 值) 元组数组
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
#返回可遍历的(键) 元组数组
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
#删除字典中指定键的健值对,并弹出指定键的键值,如果指定键不存在,则报错
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
#随机删除字典中的一个键值对,并以元组的形式弹出。字典为空则报错
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.

#如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。
| setdefault(...)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
#返回可遍历的(值) 元组数组
| values(...)
| D.values() -> an object providing a view on D's values
|

五、其他

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#遍历列表(或其他序列类型)同时获取元素索引值
for i, j in enumerate(['a','b','c']):
print(i, j)
-->
0 a
1 b
2 c

#同时遍历两个序列类型
a = ['a','b']
b = ('A','B')
for x,y in zip(a,b):
print("{} uses {}".format(x,y))
-->
a uses A
b uses B