【Python】06、python内置数
一、数据结构与获取帮助信息
1、数据结构
通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其它的数据结构。
python的最基本数据结构是序列
序列中的每个元素被分配一个序号(即元素的位置),也称为索引:索引从0开始编号
2、python中如何获取命令帮助
获取对象支持使用的属性和方法:dir(),
某方法的具体使用帮助:help()
获取可调用对象的文档字串:print(obj.__doc__)
In [15]: dir(list)
Out[15]:
['__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']
In [17]: help(list)
Help on list object:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
In [20]: print(list.__doc__)
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
In [21]: list.__doc__
Out[21]: "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"
二、列表
1、列表
列表:是一个任意类型的对象的位置相关的有序集合。
列表是一个序列,用于顺序的存储数据
列表的定义和初始化:
In [5]: lst1 = list() # 使用工厂函数list()
In [6]: lst2 = [] # 使用[]
In [7]: type(lst1)
Out[7]: list
In [8]: type(lst2)
Out[8]: list
In [9]: lst1 = list(range(10)) # 将一个可迭代对象转化为列表
In [10]: lst1
Out[10]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
通常在定义列表的时候使用中括号,在转化可迭代对象为列表时用list()
三、列表相关的操作
对列表一般有增、删、改、查的相关操作
1、查
1)通过索引(下标)访问列表的元素
返回该索引对应的元素
索引从左边开始,从0开始,不能超出范围,否则抛出IndexError
负数索引从右边开始,从-1开始
In [25]: lst1
Out[25]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [26]: lst1[0]
Out[26]: 0
In [27]: lst1[10]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-27-255d55760a91> in <module>()
----> 1 lst1[10]
IndexError: list index out of range
In [28]: lst1[-1]
Out[28]: 9
In [29]: lst1[-3]
Out[29]: 7
In [30]: lst1[-3]
2)list.index()
返回查找到该元素的第一个索引
如果该元素不存在,则抛出ValueError
start参数指定从哪个索引开始查找;stop参数指定从哪个索引结束,并且不包含该索引
start和stop可以为负数,但是总是从左往右查找
In [51]: help(lst2.index)
Help on built-in function index:
index(...) method of builtins.list instance
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
In [47]: lst2=[1, 3, 5, 2, 3, 5]
In [48]: lst2.index(3)
Out[48]: 1
In [49]: lst2.index(2)
Out[49]: 3
In [52]: lst2.index(8)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-52-857c8a1f260a> in <module>()
----> 1 lst2.index(8)
ValueError: 8 is not in list
In [56]: lst2.index(3, 3)
Out[56]: 4
In [57]: lst2.index(3, 3, 4)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-57-dd5e9d56cf7c> in <module>()
----> 1 lst2.index(3, 3, 4)
ValueError: 3 is not in list
In [59]: lst2.index(3, 3, 5)
Out[59]: 4
In [60]: lst2.index(3, 4, 5)
Out[60]: 4
In [70]: lst2.index(3, -1, -6,) # start 大于 stop 是一个空列表
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-70-b3ae59853639> in <module>()
----> 1 lst2.index(3, -1, -6,)
ValueError: 3 is not in list
In [71]: lst2.index(3, -6, -1,)
Out[71]: 1
In [74]: lst2.index(3, -6, 9,)
In [98]: lst2.index(3, 1, 1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-98-a95f8fe9908b> in <module>()
----> 1 lst2.index(3, 1, 1)
ValueError: 3 is not in list
In [99]: lst2.index(3, 1, 2)
Out[99]: 1
list.index()函数的实现原型:
def index(lst, value, start = 0, stop = -1):
i = start
for x in lst[start: end]
if x == value:
return i
i += 1
rais ValueError()
3)list.count()
返回该值在列表中出现的次数
In [89]: lst2
Out[89]: [1, 3, 5, 2, 3, 5]
In [90]: lst2.count(1)
Out[90]: 1
In [91]: lst2.count(5)
Out[91]: 2
In [92]: lst2.count(8)
Out[92]: 0
原型:
def count(lst, value):
c = 0
for x in lst:
if x == value:
c += 1
return c
小结:
index()和count()的时间复杂度是O(n),也称线性复杂度;效率与数据规模线性相关
2、改
对列表中元素的修改
修改列的元素直接使用索引取出元素并对其赋值;有且只有这一种方法能对list的单个元素做修改
In [7]: lst1 = [1, 3, 5, 2, 3, 4, 5, 6]
In [8]: lst1[2]
Out[8]: 5
In [9]: lst1[2] = 55
In [10]: lst1
Out[10]: [1, 3, 55, 2, 3, 4, 5, 6]
In [12]: lst1[15] = 15
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-12-4bd87b980f30> in <module>()
----> 1 lst1[15] = 15
IndexError: list assignment index out of range
3、增
显然不能通过索引来增加元素
1)list.append()
原地修改list,在最后增加一个元素;返回结果是None
In [13]: lst1
Out[13]: [1, 3, 55, 2, 3, 4, 5, 6]
In [14]: lst1.append(9)
In [15]: lst1
Out[15]: [1, 3, 55, 2, 3, 4, 5, 6, 9]
In [16]: lst2 = ["a", "b"]
In [17]: lst1.append(lst2)
In [18]: lst1
Out[18]: [1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b']]
2)list.insert()
在给定索引前插入一个元素;返回None
当给定的索引超过左边范围时,会在第0个元素前插入;超过右边的范围时,会在最后一个元素后插入
In [24]: lst1
Out[24]: [1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b'], 'xj']
In [25]: lst1.insert("x")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-8414f7ee6bf3> in <module>()
----> 1 lst1.insert("x")
TypeError: insert() takes exactly 2 arguments (1 given)
In [26]: lst1.insert(0, "x")
In [27]: lst1
Out[27]: ['x', 1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b'], 'xj']
In [28]: lst1.insert(20, "j")
In [29]: lst1
Out[29]: ['x', 1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b'], 'xj', 'j']
3)list.extend()
接受一个可迭代对象,将其扩展到列表后面;返回None
In [39]: lst1 = [1, 2, 3]
In [40]: lst2 = ["a", "b", "c"]
In [41]: lst1.extend(lst2)
In [42]: lst1
Out[42]: [1, 2, 3, 'a', 'b', 'c']
In [43]: lst1.extend("xxj")
In [44]: lst1
Out[44]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j']
4)+
不修改list本身,返回一个新的list,是list的连接操作
In [46]: lst1
Out[46]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j']
In [47]: lst2
Out[47]: ['a', 'b', 'c']
In [48]: lst1 + lst2
Out[48]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c']
In [49]: lst1 + ["A", "B"]
Out[49]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j', 'A', 'B']
小结:
append的时间复杂度是o(1),也被称为常数时间,效率和数据的规模无关
insert的时间复杂度是o(n),线性时间,效率和数据规模线性相关
append()操作单个元素至list尾部
extend()操作可迭代对象至list尾部
时间复杂度:是一种定性的描述一个算法的效率
4、删
1)list.remove()
删除给定值,原地修改,返回None
从左往右,删除第一个
In [60]: lst1
Out[60]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c']
In [61]: lst1.remove("a")
In [62]: lst1
Out[62]: [1, 2, 3, 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c']
In [63]: lst1.remove(5)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-63-129875e67ef4> in <module>()
----> 1 lst1.remove(5)
ValueError: list.remove(x): x not in list
2)list.pop()
删除给定索引对应的元素;不给定索引则删除最后一个索引所对应的元素
原地修改,返回该元素;
In [67]: lst1
Out[67]: [1, 2, 3, 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c']
In [68]: lst1.pop()
Out[68]: 'c'
In [69]: lst1
Out[69]: [1, 2, 3, 'b', 'c', 'x', 'x', 'j', 'a', 'b']
In [70]: lst1.pop(2)
Out[70]: 3
In [72]: lst1.pop(15)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-72-02c3871eac43> in <module>()
----> 1 lst1.pop(15)
IndexError: pop index out of range
小结:
pop()不传递Index参数时,时间复杂度O(1)
pop()传递index参数时,时间复杂度O(n)
pop()根据索引删除元素,返回删除的元素
remove根据值删除元素,返回None
3)list.clear()
删除list的所有元素
In [73]: lst1
Out[73]: [1, 2, 'b', 'c', 'x', 'x', 'a', 'b']
In [74]: lst1.clear()
In [75]: lst1
Out[75]: []
4)del()
del()是python内置函数,删除一个对象
In [167]: lst1
Out[167]: [1, ['a', 'b'], 2]
In [168]: del(lst1[1])
In [169]: lst1
Out[169]: [1, 2]
In [170]: del(lst1)
In [171]: lst1
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-171-f3e10dd48749> in <module>()
----> 1 lst1
NameError: name 'lst1' is not defined
5、list的其它操作
1)求list的长度
len()是Python内置的函数
In [76]: lst1
Out[76]: []
In [77]: len(lst1)
Out[77]: 0
In [78]: lst1 =list(range(5))
In [79]: lst1
Out[79]: [0, 1, 2, 3, 4]
In [80]: len(lst1)
Out[80]: 5
2)反转list的元素顺序
In [81]: lst1.reverse()
In [82]: lst1
Out[82]: [4, 3, 2, 1, 0]
3)排序
In [86]: print(lst1.sort.__doc__)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
In [87]: lst1
Out[87]: [4, 3, 2, 1, 0]
In [88]: lst1.sort()
In [89]: lst1
Out[89]: [0, 1, 2, 3, 4]
In [90]: lst1.append("a")
In [91]: lst1
Out[91]: [0, 1, 2, 3, 4, 'a']
In [92]: lst1.sort()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-92-0b68de07ed2f> in <module>()
----> 1 lst1.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
4)复制
In [105]: lst1
Out[105]: [0, 1, 2, 3, 4]
In [106]: lst2 = lst1 # 赋值操作是引用传递
In [107]: lst2
Out[107]: [0, 1, 2, 3, 4]
In [108]: lst2[1]
Out[108]: 1
In [109]: lst2[1] = 11
In [110]: lst2[1]
Out[110]: 11
In [111]: lst2
Out[111]: [0, 11, 2, 3, 4]
In [112]: lst1
Out[112]: [0, 11, 2, 3, 4]
赋值操作是引用传递,也被称为浅复制,浅拷贝;创建一个新的变量名,指向同一个内存对象
list.copy()
影子拷贝,并不是深拷贝
In [113]: lst1
Out[113]: [0, 11, 2, 3, 4]
In [114]: lst2 = lst1.copy()
In [115]: lst2
Out[115]: [0, 11, 2, 3, 4]
In [116]: lst2[1] = "a"
In [117]: lst2
Out[117]: [0, 'a', 2, 3, 4]
In [118]: lst1
Out[118]: [0, 11, 2, 3, 4]
深拷贝:
复制操作,对可变对象是引用传递,对不可变对象是值传递
In [123]: lst1 = [1, ["a", "b"], 2]
In [124]: lst1[1]
Out[124]: ['a', 'b']
In [125]: lst2 = lst1 # 浅复制,引用传递
In [126]: lst2
Out[126]: [1, ['a', 'b'], 2]
In [127]: lst2[1] = 0
In [128]: lst2
Out[128]: [1, 0, 2]
In [129]: lst1
Out[129]: [1, 0, 2]
In [130]: lst1 = [1, ["a", "b"], 2]
In [131]: lst2 = lst1.copy() # 影子复制,原样复制一份原内存对象,只对第一层
In [132]: lst2
Out[132]: [1, ['a', 'b'], 2]
In [133]: lst2[1] = 0
In [134]:
In [134]: lst2
Out[134]: [1, 0, 2]
In [135]: lst1
Out[135]: [1, ['a', 'b'], 2]
In [136]: lst2 = lst1.copy()
In [137]: lst2
Out[137]: [1, ['a', 'b'], 2]
In [138]: lst2[1][1] = 9
In [139]: lst2
Out[139]: [1, ['a', 9], 2]
In [140]: lst1
Out[140]: [1, ['a', 9], 2]
## copy.deepcopy()
In [149]: import copy
In [150]: lst1 = [1, ["a", "b"], 2]
In [151]: lst2 = copy.deepcopy(lst1) # 针对多层
In [152]: lst2
Out[152]: [1, ['a', 'b'], 2]
In [153]: lst2[1][1] = 9
In [154]: lst2
Out[154]: [1, ['a', 9], 2]
In [155]: lst1
Out[155]: [1, ['a', 'b'], 2]
四、元祖
1、元祖的定义和初始化
In [197]: t
Out[197]: ()
In [198]: t = ()
In [199]: t
Out[199]: ()
In [200]: t = (1, 2)
In [201]: t
Out[201]: (1, 2)
In [202]: t = 1, 2 # ()可省略
In [203]: t
Out[203]: (1, 2)
In [55]: s = 1
In [56]: type(s)
Out[56]: int
In [57]: s = 1,
In [58]: type(s)
Out[58]: tuple
In [59]: s
Out[59]: (1,)
In [204]: print(tuple.__doc__)
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.
In [205]: t = tuple() # 工厂函数tuple()
In [206]: t
Out[206]: ()
In [207]: t= tuple([1, 2, 3])
In [208]: t
Out[208]: (1, 2, 3)
In [209]: t= tuple((1, 2))
In [210]: t
Out[210]: (1, 2)
2、元祖的操作
1)索引操作
In [211]: t
Out[211]: (1, 2)
In [212]: t[1]
Out[212]: 2
In [213]: t[1] = 2 # 元祖是不可变的,不能原地修改
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-213-9d97237db197> in <module>()
----> 1 t[1] = 2
TypeError: 'tuple' object does not support item assignment
In [214]: t
Out[214]: (1, 2)
In [218]: t = (1, ["a", "b"])
In [219]: t
Out[219]: (1, ['a', 'b'])
In [220]: t[1]
Out[220]: ['a', 'b']
In [221]: t[1] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-221-636819fa7dc7> in <module>()
----> 1 t[1] = 3
TypeError: 'tuple' object does not support item assignment
In [222]: t[1][1] = 3
In [223]: t
Out[223]: (1, ['a', 3])
2)count,index()
tuple的方法只有tuple.count()和tuple.index(),表现在list中是完全一样的:
In [225]: t
Out[225]: (1, ['a', 'b'])
In [226]: t.count(1)
Out[226]: 1
In [227]: t.index(1)
Out[227]: 0
In [228]: t.index(a)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-228-7a95a64370b2> in <module>()
----> 1 t.index(a)
NameError: name 'a' is not defined
In [229]: t.index("a")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-229-71f0f19bbabb> in <module>()
----> 1 t.index("a")
ValueError: tuple.index(x): x not in tuple
In [230]: t.index(["a", "b"])
Out[230]: 1
3、命名元祖
可以通过名字替代索引来访问元素,其它方面的属性和元祖一样
In [231]: t = ("xxj", 18)
In [232]: t
Out[232]: ('xxj', 18)
In [233]: t[0]
Out[233]: 'xxj'
In [234]: t[1]
Out[234]: 18
In [235]: from collections import namedtuple # 导入collectons模块的namedtuple类
In [236]: User = namedtuple('_Yonghu', ["name", "age"]) # 类初始化
In [237]: User
Out[237]: __main__._Yonghu
In [240]: me = User("xxj", 18)
In [241]: me
Out[241]: _Yonghu(name='xxj', age=18)
In [242]: me.name
Out[242]: 'xxj'
In [243]: me.name()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-243-658c183ca1b1> in <module>()
----> 1 me.name()
TypeError: 'str' object is not callable
In [244]: me.age
Out[244]: 18
In [245]: me[0]
Out[245]: 'xxj'
In [246]: me[2]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-246-4bc5e7d46893> in <module>()
----> 1 me[2]
IndexError: tuple index out of range
In [247]: me[0] = "xj"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-247-627de02ba5b9> in <module>()
----> 1 me[0] = "xj"
TypeError: '_Yonghu' object does not support item assignment
In [249]: type(namedtuple)
Out[249]: function
In [250]: type(User)
Out[250]: type
In [251]: type(me)
Out[251]: __main__._Yonghu
In [254]: print(namedtuple.__doc__)
Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341