内置数据结构(1)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

列表及常用操作

列表是一个序列,用于顺序的存储数据。


定义与初始化

  1. lst = list() #使用list函数定义空列表

  2. lst = [] #使用中括好定义空列表

  3. lst = [1,2,3,4]#使用中括号定义带初始值的列表

  4. lst = list(range(1,10))#使用list函数把可迭代对象转化为列表。

注意:通常在定义列表的时候,使用中括号,在转化可迭代对象为列表时用list函数。


访问列表元素

1.通过下标访问,下标是从零开始。

2.当下标超出范围时,会抛出indexerror。

3.负数索引从右边开始,索引从-1开始。

4.负数索引超出范围,也会抛出indexerror。


通过value查找索引


lst = [1,2,3,4,5,6]

In:lst.index(3)

Out:2

语法:

 L.index(value, [start, [stop]])

list = [1,2,3,2,4,3,5]

###################

list.index(2) index方法返回查找的第一个索引

1

###########################

list.index(2,2)从第二个索引后查找2   start参数指定从哪个索引开始查找

3

list.index(3,2) 从第二个索引开始查找3 

##########################

list.index(2,2,3) #end参数指定到哪个索引结束,并且不包含该索引,当值不存在该范围时,会抛出ValueError

###########################

list.index(2,0,3) 索引0到3的的值(2)的索引是1

1

########################

list.index(2,-4,-1)#start 和stop参数可以为负数,但是从左往右查找

3

########################

语法:

def index(lst, value, start=0, stop=-1):

    i = start

    for x in lst[start: stop]:

        if x == value:

            return i

        i += 1

    raise ValueError

##################################

count方法返回值在列表里出现的次数

list.count(3)

2

list.count(2)

2

list.count(2)

0

####################

语法:

def count(list,value):

    c = 0

    for x in list:

        if x == value:

            c += 1

    return c

#########################

总结:

1.通过索引访问元素

2.index方法根据值返回第一个索引

3.count方法返回元素在列表里的个数

4.index和count的时间复杂度是O(n),线性复杂度,效率与数据规模线性相关。

5.凡是stop比start小,总是抛出ValueError



list元素的修改

list = [1,2,3,2,4,3,5]

list[2]

3

list[3]

2

list[3] = 5 修改列表的元素直接使用下标操作取出元素并对其赋值。

返回的list 为[1,2,3,5,4,3,5]

注意:修改元素有且只有一种方法。对超出范围得到索引修改元素,会抛出IndexError

eg:list[7] = 7 


list增加元素(无法使用索引来操作)

语法:help(lst.append)

append(...)

   L.append(object) -- append object to end

lst.append(9)

lst

[1, 2, 5, 2, 4, 3, 7, 9]

append原地修改lst,返回结果是None

########################

 help(lst.insert)

insert(...)

    L.insert(index, object) -- insert object before index


lst.insert(2,10)

lst

[1, 2, 10, 5, 2, 4, 3, 7, 9]

lst.insert(1,'a')

lst

[1, 'a', 2, 10, 5, 2, 4, 3, 7, 9]

insert也是原地修改list,返回结果是None

lst.insert(12,9)

lst.insert(100,8)

lst.insert(-100,'e')

lst

['e', 1, 'a', 2, 10, 5, 2, 4, 3, 7, 9, 9, 8]

注意:insert当索引超出范围时

索引是负数,会在第0个元素前插入,索引是整数,会在最后一个元素后插入。

append的时间复杂度是O(1)常数时间,效率和数据的规模无关,

insert的时间复杂度是O(n)线性时间,效率和数据规模线性相关。

######################################


extend(...)

    L.extend(iterable) -- extend list by appending elements from the iterable

lst.extend([1,2,3])

lst

[6, 'e', 1, 'a', 2, 10, 5, 2, 4, 3, 7, 9, 9, 8, 1, 2, 3]

lst.extend(range(2,7))

lst

[6, 'e', 1, 'a', 2, 10, 5, 2, 4, 3, 7, 9, 9, 8, 1, 2, 3, 2, 3, 4, 5, 6]

注意:原地修改,返回None。

append操作的是单个元素。

extend操作的是可迭代对象。


lst = list(range(5))

lst

[0, 1, 2, 3, 4]

lst + ['a','b','c']

[0, 1, 2, 3, 4, 'a', 'b', 'c']

lst

[0, 1, 2, 3, 4]

注意:不修改list本身,返回一个新的list,list的连续操作。


list的删除


remove(...)

    L.remove(value) -- remove first occurrence of value.

    Raises ValueError if the value is not present.


lst = [1,2,3,2,4,3,5,3,4]

lst.remove(1)#原地修改,返回None,根据值删除元素。

lst

[2, 3, 2, 4, 3, 5, 3, 4]

lst.remove(2)#从左到右删除第一个

lst

[3, 2, 4, 3, 5, 3, 4]

lst.remove(10)#当值不存在是抛出ValueError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: list.remove(x): x not in list


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.


lst.pop()#返回并删除最后一个元素

4

lst

[3, 2, 4, 3, 5, 3]

lst.pop(1)#返回并删除索引所在位置的元素

2

lst

[3, 4, 3, 5, 3]

lst.pop(100)#当删除的索引不存在时,会抛出IndexError

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IndexError: pop index out of range

lst.clear()#删除所有元素

注意pop不传递index参数时间复杂度是O(1)

   POP传递index参数时间复杂度是O(n)

   pop根据索引删除元素,并且返回删除的元素

   remove根据值删除元素,返回值为None


其他操作

求list的长度


反转

lst = list(range(4))

lst

[0, 1, 2, 3]

lst.reverse()#原地修改,返回None,翻转列表

lst

[3, 2, 1, 0]

排序


lst = []

lst = [3,1,2,4,5,7,3,2]

lst

[3, 1, 2, 4, 5, 7, 3, 2]

lst.sort()#原地修改,返回None

lst

[1, 2, 2, 3, 3, 4, 5, 7]

lst.sort(reverse=True)

lst

[7, 5, 4, 3, 3, 2, 2, 1]


复制


lst = []

lst = list(range(3))

lst

[0, 1, 2]

lst2 = lst 

lst2

[0, 1, 2]

lst2[1] = 5

lst2

[0, 5, 2]

lst

[0, 5, 2]

复制操作是引用是传递。也叫浅拷贝


copy方法

lst = [0,1,2]

lst2 = lst.copy()#影子拷贝

lst2[1] = 5

lst2

[0,5,2]

lst

[0,1,2]

赋值操作对可变对象是引用传递,对不可变对象是值传递


lst = [1,[1,2,3],2]

lst

[1,[1,2,3],2]

lst2 = lst.copy

lst2[1][1] = 5

lst2

[1,[1,5,3],2]

lst

[1,[1,5,3],2]


def copy(lst):

    tmp = []

   for i in range(lst):

    tmp.append(i)

   return tmp

深拷贝

import copy

lst2 = copy.deepcopy(lst)

lst2

[1,[1,5,3],2]

lst2[1][1] = 7

lst2

[1,[1,7,3],2]

lst

[1,[1,5,2],2]


######################

字符串极其操作 (字符串是一个集合类型并不是基本类型)

四种定义字符串的方法

s = 'hello,world'

s = "hello,world"

s = '''hello,world'''

s = """hello,world"""

其中,前两种完全一样,后两种完全一样。

s = '''hello,python
i like python'''

s

'hello,python\ni like python'

说明:三引号(单引号)可以定义多行字符串

s = 'hello,python
i like python'

  File "<ipython-input-19-99fcf475bbee>", line 1    s = 'hello,python
                     ^SyntaxError: EOL while scanning string literal

注意:单/双引号只能定义单行字符串


字符串的转义

s = 'i like \npython'

print(s)

i like 
python

s = 'i\'m summer'

s

"i'm summer"

path = 'C:\\windows\\\\nt\\system32'

path = r'C:\windows\nt\system32'#加r前缀代表此字符串是自然字符串,不会转义

print(path)


C:\windows\nt\system32

\n

print('123\n456')

123
456

\r

print('123\r456')

456

字符串的下标操作

s = 'i\'m summer'

s[1]

i

s[2]

" '"

s[3]

" "

s[4] = 'c'#字符串是不可变的

eg:

TypeError: 'str' object does not support item assignment

字符串是可迭代对象


for c in s:

    print(c)

1
'
m
 
s
u
m
m
e
r


同时字符串也可以转换为list

list(s)

['1', "'", 'm', ' ', 's', 'u', 'm', 'm', 'e', 'r']
s.count('m')
3

join操作,只有是字符串才可以join.

lst = ['i','sm','summer']

' '.join(lst)#join是字符串的方法,参数是内容为字符串的可迭代对象,接收者是分隔符


'i sm summer'

','.join(lst)

'i,sm,summer'

#字符串的分割操作

s.split

rsplit

splitlines

s = 'i love python'

s

'i love python'

s.split()#默认使用空格分割,

['i', 'love', 'python']

' i      love python'.split()#多个空格当成一个空格处理

['i', 'love', 'python']

'i      love python'.split( ' ')#当指定了以空格为分隔符时,每个空格都处理
['i', '', '', '', '', '', 'love', 'python']

s.split(maxsplit=1)
['i', 'love python']

'i i i i i i i i i i'.split(maxsplit=2)#split从左往右分割字符串,maxsplit参数表示分割多少次,默认值为-1,表示分割所有分割符
['i', 'i', 'i i i i i i i i']


'i love python'.split('o')

['i l', 've pyth', 'n']

'i love python'.split('lo')#分割符可以是任意的字符

['i ', 've python']



rsplit是split从右往左的版本

'i i i i i i '.rsplit(maxsplit=1)

['i i i i i', 'i']

'i i i i i i'.split()

['i', 'i', 'i', 'i', 'i', 'i']

'i i i i i i '.rsplit()
['i', 'i', 'i', 'i', 'i', 'i']

注意:当不是用maxsplit参数时,split和rsplit的表现形式是一样的,但是split的效率高于rsplit

s.splitlines()
s.splitlines()#按行分割,并且返回结果不带操作符
['i am summer', 'i love python']

s.splitlines(True)#按行分割,并且返回结果带换行符
['i am summer\n', 'i love python']

help(str.partition)
partition(...)
    S.partition(sep) -> (head, sep, tail)
    
    Search for the separator sep in S, and return the part before it,
    the separator itself, and the part after it.  If the separator is not
    found, return S and two empty strings.

     'i am summer'.partition(' ')#总是返回一个三元组,它按传入的分割符分割一次,得到head ,tail,返回结果      是head,sep,tail
   ('i', ' ', 'am summer')  
   
 
注意: rpartition 是partition从右往左的版本  
   
cfg = 'mysql.connect=mysql://user:passwd@127.0.0.1:3307/test'  
cfg.partition('=') 
('mysql.connect', '=', 'mysql://user:passwd@127.0.0.1:3307/test')

cfg = 'env=PATH=/usr/bin:$PATH' 
cfg.partition('=')  
('env', '=', 'PATH=/usr/bin:$PATH') 

' '.partition('=')
(' ', '', '')
 
cfg.split('=')
['env', 'PATH', '/usr/bin:$PATH']


解释:
def partition(s,sep):
    if s =='':
        return '','',''
    tmp = s.split(sep,maxsplit)
    if len(tmp) == 2:
        return tmp[0],sep,tmp[1]
    if len(tmp) == 1:
        return tmp[0],'',''

字符串大小写转换和排版
s = 'test'
s.upper()
'TEST'
    
s.upper().lower()    
'test'    
    
s.title()
'Test'

'i love python'.title()#每个单词首字符大写
'I Love Python'

s.capitalize()
'Test'

'i love python'.capitalize()#句子首字母大写
'I love python'

s.center(7)
'  test '

s.zfill(8)
'0000test'

s.casefold()#统一转换为大写,或者统一转换为小写,在不同的平台下有不同的表现形式,但是在同一平台下,表现形式相同,通常用来忽略大小写时的比较
'test'

'Test  TTest'.casefold()
'test  ttest'

'\t'.expandtabs(4)
'    '

字符串的修改


s.replace
s.strip
s.lstrip
s.rstrip
s.ljust
s.rjust

s = 'i love python'
s.replace('love','give up')#replace返回一个新的字符串,使用new替换old
'i give up python'

s = 'i very very love python'
s.replace('very','not')#有多少个替换多少个
'i not not love python'


s.replace('very','not',1)#可选的count参数,指定替换多少次
'i not very love python'



help(str.strip)
strip(...)
    S.strip([chars]) -> str
    
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

s = '   hahahah  hahahah   '
s.strip()#strip用来移除字符串前后的空格
'hahahah  hahahah'

s = '\n \r \t hahaha hahaha \t \n \r'
s.strip()#strip移除字符串前后的空白
'hahaha hahaha'


s = '####haha ## haha  ###'
s.strip('#')#可以指定移除的字符
'haha ## haha  '

s = '{{  haha  haha  }}'
s.strip('{}')#可以指定移除多个字符
'  haha  haha  '


s.lstrip('{}')#lstrip表现和strip一样。但是只处理左端

' hahha haha}}'

s.rstrip('{}')#rstrip表现和strip一样,但是只处理右端
'{{ hahha haha'


s = 'test'
s.ljust(10)#ljust原字符串在左边
'test      '

s.rjust(10)#rjust原字符串在左边
'      test'

s.center(10)#原字符串在中间
'   test   '


s.center(10,'#')#可以指定填充字符
'###test###'

s.ljust(10,'#')
'test######'

s.center(10,'##')#填充字符串长度只能为1
TypeError: The fill character must be exactly one character long


s.center(3)#如果宽度小于等于原字符串长度,不做任何操作
'test'
s.center的左边优先级高于右边


字符串的查找
* s.find
* s.index
* s.count
* s.rfind
* s.rindex

s = 'i love python'
s.find('love')#从左往右查找,找到第一个子串love 返回子串首字母的索引
2
s.find('love1')#当子串不存在的时候,返回-1
-1


s = 'i very very love python'
s.find('very')
2

s.find('very',3)#start参数可以指定从哪里开始查找
7

s.find('very',3,5)#end参数指定到哪里结束,end不包含
-1

s.find('very',3,11)
7

s.rfind('very')#rfind是find的从右往左的版本
7

s.rfind('very',8)#start和stop意义一样,是先根据start和stop截取字符串,再查找。索引总是从左往右
-1

help(s.index)

index(...) method of builtins.str instance
    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.

s.index('very')
2

s.index('very',3)
7

s.index('very',8)#index查找当子串不存在时,抛出valueerror
ValueError: substring not found

s.find('very',8)#find查找,子串不存在时返回-1
-1
s.rindex('very')#rindex时index从右往左的版本
7

s.count('very')
2

s.count('haha')
0

s.count('very',3)
1

list(enumerate(s))

[(0, 'i'),
 (1, ' '),
 (2, 'v'),
 (3, 'e'),
 (4, 'r'),
 (5, 'y'),
 (6, ' '),
 (7, 'v'),
 (8, 'e'),
 (9, 'r'),
 (10, 'y'),
 (11, ' '),
 (12, 'l'),
 (13, 'o'),
 (14, 'v'),
 (15, 'e'),
 (16, ' '),
 (17, 'p'),
 (18, 'y'),
 (19, 't'),
 (20, 'h'),
 (21, 'o'),
 (22, 'n')]

字符串的判断
* s.startswith
* s.endswith
* s.is*
s.startswith('i very')#判断字符串是否以某个前缀开始,返回结果是bool类型
True

s.startswith('abc')
False

s.startswith('very',2)#start参数表示的是从索引start处开始比较,返回值是bool类型
True

s.startswith('very',2,5)#end表示从索引end处停止比较
False

s.endswith('python')#判断字符串是否以某个后缀结尾,返回bool类型
True

s.endswith('python',17)#start参数表示从索引start处开始比较
True


s.endswith('python',0,22)#end参数表示到索引end为止,不包含end
False

help(s.isalnum)
isalnum(...) method of builtins.str instance
    S.isalnum() -> bool
    
    Return True if all characters in S are alphanumeric
    and there is at least one character in S, False otherwise.

s.isalnum()
False

'a'.isalnum()
True

合法的标识符是字母或者下划线开头,仅包含字母数字和下划线
'a'.isidentifier()
True

'27'.isidentifier()
False

'class'.isidentifier()
True

字符串的格式化是拼接字符串的一种手段
1.''.join(['i', 'love', 'python'])
2.'i' + 'love' +'python'

返回结果:'ilovepython'   join 和 + 难以控制格式

printf style 字符串格式化 从c语言继承过来的
s ='i love %s' #待格式化的字符串,当一个字符串存在占位符的时候,占位符:%加一个格式控制符
s % ('python',)#传入参数顺序的替换占位符,返回替换后的字符串,原串不变。
'i love python'

'i love %s,i am %d'%('python',18)
'i love python,i am 18'


'i love %s,i am %d'%('python',)#占位符个数和参数个数不匹配的时候,会抛出typeError

s = 'i love %s,i am %d'

s % ('python',18 )

'i love python,i am 18'

s % ('python','18')#当类型不匹配时,会抛出TypeError
s % (18,18)#当占位符是%s,其实隐式调用了str()  %r隐式调用了
'i love 18,i am 18'

练习:s = 'i love %s , i am %s , i am %d' % ('python','summer',19)
print(s)
i love python , i am summer , i am 19

字符串原样输出:print('%s %%d' % 'haha')
haha %d

printf style 格式化对从其他语言,尤其是c语言转过来的,容易接受,但是Python所推荐的方法
s = 'i love {}'format方法使用大括号作为占位符

。。。。。。。。。











本文转自 妙曼  51CTO博客,原文链接:http://blog.51cto.com/yanruohan/1898583,如需转载请自行联系原作者
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
1月前
|
存储 C++
c++数据结构
c++数据结构
28 0
|
3天前
|
存储 算法 C#
C#编程与数据结构的结合
【4月更文挑战第21天】本文探讨了C#如何结合数据结构以构建高效软件,强调数据结构在C#中的重要性。C#作为面向对象的编程语言,提供内置数据结构如List、Array和Dictionary,同时也支持自定义数据结构。文章列举了C#实现数组、链表、栈、队列等基础数据结构的示例,并讨论了它们在排序、图算法和数据库访问等场景的应用。掌握C#数据结构有助于编写高性能、可维护的代码。
|
25天前
|
存储 算法
【数据结构】什么是数据结构?
【数据结构】什么是数据结构?
10 0
|
29天前
|
算法 C++ 开发者
【C/C++ 数据结构 】 连通图的基本了解
【C/C++ 数据结构 】 连通图的基本了解
30 0
|
5月前
|
存储 算法 容器
数据结构 > 什么是数据结构?
数据结构 > 什么是数据结构?
|
8月前
|
存储 机器学习/深度学习
|
10月前
|
存储 算法 C语言
初识数据结构
初识数据结构
51 0
|
存储 算法 安全
【数据结构】C#实现常用数据结构总结
自行整理的C#常见数据结构笔记。
315 0
【数据结构】C#实现常用数据结构总结
|
存储 算法 C语言
数据结构成神篇1-初学数据结构
今天我们开始数据结构的学习,当然,这个有些概念是十分抽象的,只看文章是不一定能懂的,或者说会耗费不少的时间。所以我会持续在B站上面更新讲解视频,都是自己的一些理解和想法。会拿出来和大家一起分享,都是免费的。原创不易,希望大家可以三连支持一下,也希望能给大家带来进步。
65 0
数据结构成神篇1-初学数据结构
数据结构4-什么是数据结构2
数据结构4-什么是数据结构2
46 0
数据结构4-什么是数据结构2