python的基本数据结构:列表、元组、集合、字典。python的各种库有自己的数据结构,但是都由这些基本的数据结构组合而成。
python本身支持了很多类似C库函数功能的内在函数我们可以输入dir(builtins)指令来查看他们
dir(__builtins__)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EnvironmentError',
'Exception',
'False',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'WindowsError',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'abs',
'all',
'any',
'ascii',
'bin',
'bool',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
当我们遇到没见过的函数可以使用help()来看他的具体说明
help(id)
Help on built-in function id in module builtins:
id(obj, /)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
最基本的数据结构list
1、列表定义
1)列表是python的一个内建数据结构
2)可以把列表看做一个容器
3)该容器被隔成不同的空间,每个空间可以放任何类型“物”
4)列表内物体只有前后的位置关系
5)列表每个格子中的“物”是可以替换的
6)列表是一个可变的序列
dir(list)
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
按照“增”“删”“改”“查”四种基本操作把上面的方法归归类
“增”操作包括:append(),extend(),insert()
list1 = ['abc',123,['I love u','我爱你']]
list1.append(['增加','difference between append and extend'])
list1
['abc',
123,
['I love u', '我爱你'],
['增加', 'difference between append and extend']]
append()如上如所示可以给列表添加一个元素到末尾,我们只需在我们的列表后添加.append(要添加的内容),输入要添加的内容即可.
extend()用法:
extend的功能和append有点像,但不同的是append加入的是对象,而extend加入的是元素。
调用append他所添加的内容只会被看做一个对象,队列长度只会加一,而extend会分别把其中各个元素放入原列表中
list1 = ['abc',123,['I love u','我爱你']]
list1.extend(['增加','difference between append and extend'])
list1
['abc', 123, ['I love u', '我爱你'], '增加', 'difference between append and extend']
list.insert(index,obj),index为要插入元素的位置,从0开始
list1 = ['abc',123,['I love u','我爱你']]
list1.insert(2,'insert')
list1
['abc', 123, 'insert', ['I love u', '我爱你']]
删除包含以下几种方法:clear(),remove(),pop()
clear()可以算得上是核武器级别的删除,一次性删除所有的元素,切记慎用
list1 = ['abc',123,['I love u','我爱你']]
list1.clear()
list1
[]
remove()方法相比clear他就要温柔的多了,他只会删除指定的元素
list1 = ['abc',123,['I love u','我爱你']]
list1.remove(123)
list1
['abc', ['I love u', '我爱你']]
POP(),学习过汇编的同学可能会知道POP是用来出栈的,这里我们调用POP时效果类似出栈会将最后一个元素删除
list1 = ['abc',123,['I love u','我爱你']]
list1.pop()
list1
['abc', 123]
使用python的保留字 del 对列表的元素或部分片段进行删除
list1 = ['abc',123,['I love u','我爱你']]
del list1[0]
list1
[123, ['I love u', '我爱你']]
“改”主要包含以下方法:copy(),reverse()和sort()
sort()就是排序
list1 = ['abc',123,['I love u','我爱你']]
list1.sort()
list1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-1177e0291cf7> in <module>()
1 list1 = ['abc',123,['I love u','我爱你']]
----> 2 list1.sort()
3 list1
TypeError: '<' not supported between instances of 'int' and 'str'
list1 = [0,7,2,9,5,3]
list1.sort()
list1
[0, 2, 3, 5, 7, 9]
sort()方法默认是按顺序排列,从小到大依次排列,如果你需要逆序排列可以输入参数reverse=True(注意大小写),值得提醒的是sort()只能对一种数据类型进行排列
list1 = [0,7,2,9,5,3]
list1.sort(reverse=True)
list1
[9, 7, 5, 3, 2, 0]
reverse()方法,人如其名它的作用就是让整个队列倒序排布
list1 = ['abc',123,['I love u','我爱你']]
list1.reverse()
list1
[['I love u', '我爱你'], 123, 'abc']
copy()方法,list2=list1.copy()能够将list1拷贝到list2中
list1 = ['abc',123,['I love u','我爱你']]
list2 = list1.copy()
list2
['abc', 123, ['I love u', '我爱你']]
print (id(list1),id(list2))
2205845460744 2205845460808
”查“,主要包含以下几个函数:count(),index()
count()计数,我们可以利用这一方法简单计算出对列中某一元素的具体数值
list1 = ['abc',123,['I love u','我爱你']]
list1.count(123)
1
index()方法能够将列表中某一元素的具体位置反映出来
list1 = ['abc',123,['I love u','我爱你']]
list1.index('abc')
0
list切片slice
a=[1,2,3,"alex",9,4,5,6,7,8]
b=a[1:9:2] #【起始:结束:步长】
print (b)
c = a[0:-3]
print(c)
d =a[-3:]
print(d)
[2, 'alex', 4, 6]
[1, 2, 3, 'alex', 9, 4, 5]
[6, 7, 8]
可以通过list切片操作实现list‘增’、‘删’、‘改’
# 增加list元素
list1=['abc',123,['I love u','我爱你']]
list1[2:] =["hello","world","alex","rose"]
print(list1)
list1=['abc',123,['I love u','我爱你']]
list1[1:1] = ['a','b','c']
print (list1)
['abc', 123, 'hello', 'world', 'alex', 'rose']
['abc', 'a', 'b', 'c', 123, ['I love u', '我爱你']]
# 删除list元素
list1=['abc',123,['I love u','我爱你']]
list1[1:] = []
print (list1)
['abc']
# 修改list元素
list1=['abc',123,['I love u','我爱你']]
list1[2] = 'love u'
print (list1)
['abc', 123, 'love u']
python常用 list 函数
cmp(list1,list2):比较两个list
len(list1),获取list1的长度
max(list1),获取list1中元素最大值
min(list1),获取list1中元素最小值
sum(list1),获取list1所有元素的和
list(seq),将元组转化为list