python的数据结构有哪些_Python的数据结构

一、Python中有哪些数据结构?

dict, list, tuple, set, str

二、dict, list, tuple, set, str的特点

dict:字典,由键值对构成,通过键值对字典中元素进行索引,是可变数据结构

list:列表,列表中的元素可以是任意类型,通过下标进行索引,是可变数据结构

tuple:元组,元组中的元素可以是任意类型,通过下标进行索引,其中的元素不可变

str:字符串,通过下表索引,元素不可变

set:元素不能重复,不能按照下标索引,

三、dict详解

dict1 = {'name':'Andy', 'age':29}

print(dir(dict1))#查看字典所有方法

'''['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__','__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__','__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__','__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__','__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__','__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys','pop', 'popitem', 'setdefault', 'update', 'values']'''

print(help(dict1.clear))

'''Help on built-in function clear:clear(...) method of builtins.dict instanceD.clear() -> None. Remove all items from D.None'''

print(help(dict1.get))

'''Help on built-in function get:get(...) method of builtins.dict instanceD.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.None'''

字典的创建、清空字典元素

dict = {'name':'Andy', 'age':29}#创建一个字典

print(dict)#{'name': 'Andy', 'age': 29}

print(type(dict))#

print(id(dict))#159307528

dict.clear()#清空字典里的所有元素,()中的变量是self也就是字典本身

print(dict)#{}

print(id(dict))#删除了之后还是原来的内存地址,159307528

字典中的方法

len()

dict1 = {'name':'Andy', 'age':29}

print(len(dict1))#2

popitem()

dict1 = {'name':'Andy', 'age':29}

result = dict1.popitem()

print(result)#('age', 29)

print(type(result))#

print(dict1)#{'name': 'Andy'}

setdefault()

dict1 = {'name':'Andy', 'age':29}

result1 = dict1.setdefault('nationality', 'China')#nationality这个键不存在,添加

print(result1)#China

print(type(result1))#

print(dict1)#{'name': 'Andy', 'age': 29, 'nationality': 'China'}

result2 = dict1.setdefault('name', 'Cassie')#name这个键已经存在,不添加

print(result2)#Andy

print(dict1)#{'name': 'Andy', 'age': 29, 'nationality': 'China'}

update()

#第一种用法

dict1 = {'name':'Andy', 'age':29}

dict1.update(score = 99, sex = 'male')

print(dict1)#{'name': 'Andy', 'age': 29, 'score': 99, 'sex': 'male'}

#第二种用法

dict1 = {'name':'Andy', 'age':29}

dict2 = {'score':99, 'sex':'male'}

dict1.update(dict2)

print(dict1)#{'name': 'Andy', 'age': 29, 'score': 99, 'sex': 'male'}

#第三种用法

dict1 = {'name':'Andy', 'age':29}

list = [('score', 99), ('sex', 'male')]#这里可以是元组套元组,元组套列表,列表套元组,列表套列表

dict1.update(list)

print(dict1)#{'name': 'Andy', 'age': 29, 'score': 99, 'sex': 'male'}

#这三种方法实际区别是装新增元素的容器不同,第一种不要容器直接把表达式作为参数,第二种用字典作为容器,第三种用元组或者列表作为容器

keys()

dict1 = {'name':'Andy', 'age':29}

result = dict1.keys()

print(result)#dict_keys(['name', 'age'])

print(type(result))#

#print(result[0], result[1], end = " ")#TypeError: 'dict_keys' object does not support indexing

values()

dict1 = {'name':'Andy', 'age':29}

result = dict1.values()

print(result)#dict_values(['Andy', 29])

print(type(result))#

items()

dict1 = {'name':'Andy', 'age':29}

result = dict1.items()

print(result)#dict_items([('name', 'Andy'), ('age', 29)])

print(type(result))#

说明:keys() values() items()三个方法取出的内容的类型不支持索引,但是可以用for in进行遍历

四、list详解

list1 = [1, 2, 3, 4]

print(dir(list1))

'''['__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']

len()

list1 = [1, 2, 3, 4]

print(len(list1))#4,len()是面向过程的方法

append()

list1 = [1, 2, 3, 4]

print(id(list1))#178795976

list2 = list1.append(5)

print(list1)#[1, 2, 3, 4, 5]

print(id(list1))#178795976 修改后list1的内存地址不变

print(list2)#None 说明系统在定义list的append方法时没有返回值

clear()

list1 = [1, 2, 3, 4]

print(help(list1.clear))

print(list1.clear())#None clear方法的内置函数没有返回值

print(list1)#[]

'''Help on built-in function clear:clear(...) method of builtins.list instanceL.clear() -> None -- remove all items from LNone'''

copy()

list1 = [1, 2, 3, 4]

list2 = list1

list3 = list1.copy()

#查看一下copy的用法

print(help(list1.copy))

'''Help on built-in function copy:copy(...) method of builtins.list instanceL.copy() -> list -- a shallow copy浅拷贝 of LNone'''

#查看各个list的地址

print(id(list1))#178685256

print(id(list2))#178685256

print(id(list1.copy()))#178881288

print(id(list3))#179044552

print(list1.copy)

'''注意1:赋值语句list2 = list1意思是list2指向整个list2这个列表的地址注意2:list3 = list1.copy()的意思是list3中每个元素指向list1中每个元素的地址,而不是整个list3的地址指向list1的地址,这就是为什么id(list1)不等于id(list3)注意3:为什么list.copy()和list3两者的地址不同,一个是list1这个列表实例copy()方法的地址(也就是一个函数在内存中的地址),一个是list3这个列表的地址,所以不同注意4:print(list1.copy)返回(表示这个list对象的copy方法或者说函数的地址,从help中可以看到copy的返回值为None)'''

#查看各个list的内容

print(list1)#[1, 2, 3, 4]

print(list2)#[1, 2, 3, 4]

print(list3)#[1, 2, 3, 4]

print(list1.copy())#[1, 2, 3, 4]

print(list1.copy)#

#查看改变后的各个list及其地址

list1.append(5)

print(list1)#[1, 2, 3, 4, 5]

print(id(list1))#178685256

print(list2)#[1, 2, 3, 4, 5]

print(id(list2))#178685256

print(list3)#[1, 2, 3, 4]

print(id(list3))#179044552

a = list1[0]

b = list2[0]

c = list3[0]

print(id(a))#1723100640

print(id(b))#1723100640

print(id(c))#1723100640

#由此可见list1 list2 list3中每个元素地址是一样的,所以这里的浅拷贝

list1[0] = 100

print(list1)

print(list2)

print(list3)

a = list1[0]

b = list2[0]

c = list3[0]

print(id(a))#1723103808

print(id(b))#1723103808

print(id(c))#1723100640

#当修改了list[0]的指向的时候,list3仍然指向之前拷贝的指向

count()

list1 = [1, 2, 3, 4]

print(help(list1.count))

'''Help on built-in function count:count(...) method of builtins.list instanceL.count(value) -> integer -- return number of occurrences of valueNone'''

extend()

list1 = [1, 2, 3, 4]

print(help(list1.extend))

'''Help on built-in function extend:extend(...) method of builtins.list instanceL.extend(iterable) -> None -- extend list by appending elements from the iterableNone'''

index()

list1 = [1, 2, 3, 4]

print(help(list1.index))

'''Help on built-in function index:index(...) method of builtins.list instanceL.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present.None'''

insert()

list1 = [1, 2, 3, 4]

print(help(list1.insert))

'''Help on built-in function insert:insert(...) method of builtins.list instanceL.insert(index, object) -- insert object before indexNone'''

pop()

list1 = [1, 2, 3, 4]

print(help(list1.pop))

'''Help on built-in function pop:pop(...) method of builtins.list instanceL.pop([index]) -> item -- remove and return item at index (default last).Raises IndexError if list is empty or index is out of range.None'''

remove()

list1 = [1, 2, 3, 4]

print(help(list1.remove))

'''Help on built-in function remove:remove(...) method of builtins.list instanceL.remove(value) -> None -- remove first occurrence of value.Raises ValueError if the value is not present.None'''

reverse()

list1 = [1, 2, 3, 4]

print(help(list1.reverse))

'''Help on built-in function reverse:reverse(...) method of builtins.list instanceL.reverse() -- reverse *IN PLACE*None'''

sort()

list1 = [1, 2, 3, 4]

print(help(list1.sort))

'''Help on built-in function sort:sort(...) method of builtins.list instanceL.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*None'''

__add__()

list1 = [1, 2, 3, 4]

print(help(list1.__add__))

'''Help on method-wrapper object:__add__ = class method-wrapper(object)| Methods defined here:|| __call__(self, /, *args, **kwargs)| Call self as a function.|| __eq__(self, value, /)| Return self==value.|| __ge__(self, value, /)| Return self>=value.|| __getattribute__(self, name, /)| Return getattr(self, name).|| __gt__(self, value, /)| Return self>value.|| __hash__(self, /)| Return hash(self).|| __le__(self, value, /)| Return self<=value.|| __lt__(self, value, /)| Return self

三、str详解

str1 = 'andyhujinzhao'#定义一个字符串

print(dir(str1))

'''['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__','__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__','__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__','__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__','__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__','__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize','casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find','format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit','isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle','isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition','replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip','split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate','upper', 'zfill']'''

capitalize()

str1 = 'andyhujinzhao'#定义一个字符串

print(str1.capitalize())#Andyhujinzhao

print(help(str1.capitalize))

'''Help on built-in function capitalize:capitalize(...) method of builtins.str instanceS.capitalize() -> strReturn a capitalized version of S, i.e. make the first characterhave upper case and the rest lower case.None'''

casefold()(大写转为小写,Unicode编码时用casefold,lower()只对 ASCII码 也就是‘A-Z’有效,不能将其他语言的大写转为小写,比如德语中'ß'的小写是'ss')

str1 = 'ANDYHUJINZHAO'#定义一个字符串

str2 = 'ß'

print(str2.casefold())#ss

print(str1.casefold())#andyhujinzhao

print(help(str1.casefold))

'''Help on built-in function casefold:casefold(...) method of builtins.str instanceS.casefold() -> strReturn a version of S suitable for caseless comparisons.None'''

center()

str1 = 'andyhujinzhao'

print(str1.center(20, '@'))#字符串的字符数加上fill character共计20个

#@@@andyhujinzhao@@@@

print(help(str1.center))

'''Help on built-in function center:center(...) method of builtins.str instanceS.center(width[, fillchar]) -> strReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)None'''

count()

str1 = 'andyhujinzhao'

print(str1.count('a'))#2

print(help(str1.count))

'''Help on built-in function count:count(...) method of builtins.str instanceS.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end]. Optional arguments start and end areinterpreted as in slice notation.None'''

encode()(Python encode()方法以encoding 指定的编码格式编码字符串,errors参数可以指定不同的错误处理方案,默认为 'strict',意为编码错误引起一个UnicodeError, 其他可能的值有'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过codecs.register_error()注册的任何值)

str1 = 'andyhujinzhao'

print(str1.encode())#b'andyhujinzhao'

print(help(str1.encode))

'''Help on built-in function encode:encode(...) method of builtins.str instanceS.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec编解码器 registered for encoding. Default encodingis 'utf-8'. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that can handle UnicodeEncodeErrors.None'''

endswith()

str1 = 'andyhujinzhao'

print(str1.endswith('ao'))#True

print(help(str1.endswith))

'''Help on built-in function endswith:endswith(...) method of builtins.str instanceS.endswith(suffix[, start[, end]]) -> boolReturn True if S ends with the specified suffix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try.None'''

expandtabs()

str1 = 'andy\thujinzhao'

print(str1.expandtabs())#andy hujinzhao

find()

str1 = 'andyhujinzhao'

print(help(str1.find))

'''Help on built-in function find:find(...) method of builtins.str instanceS.find(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure.None'''

print(str1.find('z'))#9

??????format()

str0 = 'andy'

str1 = 'hujinzhao'

str2 = 'love'

str3 = 'andox'

print(help(str1.format))

'''Help on built-in function format:format(...) method of builtins.str instanceS.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').None'''

print('{3} {0} {3},{2} "name":{1}'.format(str0, str1, str2, str3))

#andox andy andox,love "name":hujinzhao 逗号和空格都会被打印出来

#{i} i给出了从后面的哪个位置取字符串,参数可以是*args或者**kwargs

??????format_map()

index()

str0 = 'hujinzhaoandy1234567890'

print(help(str0.index))

'''Help on built-in function index:index(...) method of builtins.str instanceS.index(sub[, start[, end]]) -> intsub指的是子串,[]表示可选参数:①外层[]表示[, start[, end]]可以都不要,即:S.index(sub)②如果要外层[]内的内容,分为两种情况:不要end参数,即S.index(sub, start)要end参数,即:S.index(sub, start, end)Return the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Raises ValueError when the substring is not found.None'''

print(str0.index('n', 1, 5))#4

print(str0.index('n', 1, 2))#ValueError: substring not found

isalnum() isalpha()

str0 = 'hujinzhaoandy1234567890'

print(help(str0.isalpha))

'''Help on built-in function isalpha:isalpha(...) method of builtins.str instanceS.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise.None'''

print(str0.isalpha())#False

isdecimal()

str0 = '1234567890'

print(help(str0.isdecimal))

'''

isdecimal(...) method of builtins.str instance

S.isdecimal() -> bool

Return True if there are only decimal characters in S,

False otherwise.

None

'''

print(str0.isdecimal())#True

isdigit()

str0 = '0001234567890'

print(help(str0.isdigit))

'''isdecimal(...) method of builtins.str instanceS.isdecimal() -> boolReturn True if there are only decimal characters in S,False otherwise.None'''

print(str0.isdigit())#True

isidentifier()

str0 = '0001234567890'

str1 = '_'

str2 = 'def'

str3 = 'ass123'

print(help(str0.isidentifier))

'''

Help on built-in function isidentifier:

isidentifier(...) method of builtins.str instance

S.isidentifier() -> bool

Return True if S is a valid identifier标识符 according

to the language definition.

Use keyword.iskeyword() to test for reserved identifiers

such as "def" and "class".

None

在python里,标识符有字母、数字、下划线组成

在python中,所有标识符可以包括英文、数字以及下划线_,但不能以数字开头

python中的标识符是区分大小写的

以下划线开头的标识符是有特殊意义的,以单下划线开头(_foo)的代表不能直接访问的类属性

需通过类提供的接口进行访问,不能用“from xxx import *”而导入

以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)

代表python里特殊方法专用的标识,如__init__()代表类的构造函数

'''

print(str0.isidentifier())#False

print(str1.isidentifier())#True

print(str2.isidentifier())#True

print(str3.isidentifier())#True

islower() isupper()

print(help(str.islower))

'''Help on method_descriptor:islower(...)S.islower() -> boolReturn True if all cased characters in S are lowercase小写字母 and there isat least one cased character in S, False otherwise.None'''

isnumeric()

print(help(str.isnumeric))

'''Help on method_descriptor:isnumeric(...)S.isnumeric() -> boolReturn True if there are only numeric characters in S,False otherwise.None'''

isprintable()

isspace()

istitle()

join()

ljust()

lower()

lstrip()

maketrans()

partition()

replace()

rfind()

rindex()

rjust()

rpartition()

rsplit()

rstrip()

split()

splitlines()

startswith()

strip()

swapcase()

title()

translate()

upper()

zfill()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值