Python从0到1之数据序列

字符串

字符串是Python中最常见的数据类型,我们可以用’'或""号创建字符串

x = "hello world"
print(x) # hello world

坐标

坐标可以精确找到序列中的字符

s = "hello world"
s[0] # 'h'
s[-1] # 'd'

切片

截取序列中的一部分
序列名[开始位置下标(默认0):结束位置下标(默认最后位置+1):步长(默认1)] 不包含结束位置,步长可以为负数,表示倒序取,字符串、列表、元组都支持切片操作

s="abcdefg"
s[:] # 'abcdefg' 不写开头表示从头取,不写结尾表示取到最后
s[2:5] # 'cde'
s[::2] # 'aceg'
s[::-1] #'gfedcba' 步长负数表示倒序取
s[-5:-1:-1] # '' 方向和步长冲突,取不到数据

find()

find()
检查某个子串是否在字符串中,如果在返回开始位置下标,否则返回-1
字符串.find(子串,开始位置下标,结束位置下标) 省略下标表示查找整个字符串

mystr = 'you and me and he'
mystr.find('and') # 4
mystr.find('anda') # -1 查找的子串不存在,返回-1
mystr.find('and',8,16) # 11

rfind() 和find相同,表示从右侧开始查找

mystr = 'you and me and he'
mystr.rfind('and') # 11

index()

index()
检查某个子串是否在字符串中,如果在返回开始位置下标,否则报错
字符串.index(子串,开始位置下标,结束位置下标) 省略下标表示查找整个字符串

mystr = 'you and me and he'
mystr.index('and') # 4
mystr.find('anda') # 报错ValueError: substring not found

rindex()和index相同,表示从右侧开始查找

mystr = 'you and me and he'
mystr.rindex('and') # 11

count()

返回某个子串在字符串中出现的次数
字符串.count(子串,开始位置下标,结束位置下标)省略下标表示查找整个字符串

mystr = 'you and me and he'
mystr.count('and') # 2
mystr.count('and',8,16) # 1

replace()

str.replace(old, new,num)
次数可以省略,如果替换次数超过子串出现次数,则替换次数为子串出现次数
不可变类型:不能直接修改数据的类型即为不可变类型
字符串是不可变类型,原字符串不会被改变

mystr = 'you and me and he'
mystr.replace('and','or') # 'you or me or he'
mystr.replace('and','or',1) # 'you or me and he' 替换1次
mystr.replace('and','or',10) # 'you or me and he' 替换多次

split()

split()
通过指定字符对字符串进行切片,返回列表
字符串.split(分割字符,num)
num表示分割次数,返回的数据为num+1个,num可以省略
分割字符是原有字符串的子串,分割后丢失该子串

mystr = 'you and me and he'
mystr.split('and') # ['you ', ' me ', ' he']
mystr.split('and',1) # ['you ', ' me and he']

rsplit() 和split()一样表示从右侧开始分割

mystr = 'you and me and he'
mystr.rsplit('and') # ['you ', ' me ', ' he']
mystr.rsplit('and',1) # ['you and me ', ' he']

splitlines() 表示按行分割字符串

"a\nb\nc".splitlines() # ['a', 'b', 'c']

strip()

strip()
清除两侧空白,也可以删除指定字符

 "   abc   ".strip() # 'abc'
 "xxxabcxxx".strip("x") # 'abc'

lstrip()
清除左侧空白,也可以删除指定字符

 "   abc   ".lstrip() # 'abc   '
 "xxxabcxxx".lstrip("x") # 'abcxxx'

rstrip()
清除右侧空白,也可以删除指定字符

 "   abc   ".rstrip() # '   abc'
 "xxxabcxxx".rstrip("x") # 'xxxabc'

join()

将序列中的元素以指定字符连接成新的字符串

mylist = ['a','b','c']
' '.join(mylist) # 'a b c'
mystr = 'abc'
' '.join(mystr) # 'a b c'

补充字符串

ljust()

返回左对齐字符串,并使用指定字符(默认空格)填充对应字符串长度
字符串.ljust(长度,填充字符)

"hello".ljust(10) # 'hello     '
"hello".ljust(10,"*") # 'hello*****'
rjust()

返回右对齐字符串,并使用指定字符(默认空格)填充对应字符串长度
字符串.rjust(长度,填充字符)

"hello".ljust(10) # '     hello'
"hello".ljust(10,"*") # '*****hello'
center()

返回中间对齐字符串,并使用指定字符(默认空格)填充对应字符串长度
字符串.center(长度,填充字符)

"hello".ljust(10) # '  hello   '
"hello".ljust(10,"*") # '**hello***'
zfill()

字符串前面补0

"hello".zfill(10) # '00000hello'

大小写转换

# capitalize() 第一个单词首字母大写
'you and me and he'.capitalize() # 'You and me and he'
# title() 首字母都大写
'you and me and he'.title() # 'You And Me And He'
# lower() 转小写
"abcDEF".lower() # 'abcdef' 
# upper() 转大写
"abcDEF".upper() # 'ABCDEF' 
# swapcase() 大小写互转
"abcDEF".swapcase() # 'ABCdef' 

判断

类型

# isalpha() 判断是否都是字母,是返回True,否则返回else
"abc".isalpha() # True
"abc123".isalpha() # False
# isdigit() 判断是否都是数字,是返回True,否则返回else
"123".isdigit() # True
"123abc".isdigit() # False
# isalnum() 判断是否都是数字或字母,是返回True,否则返回else
"123abc".isalnum() # True
"123abc@".isalnum() # False
# isspace() 判断是否都是空格,是返回True,否则返回else
"  \n".isspace() # True
"  \na".isspace() # False
# islower() 判断是否都是小写字母,是返回True,否则返回else
"abc".islower() # True
"Abc".islower() # False
# isupper() 判断是否都是大写字母,是返回True,否则返回else
"ABC".isupper() # True
"Abc".isupper() # False
# istitle() 判断首字母是否都大写,是返回True,否则返回else
"Hello World".istitle() # True
"Hello world".istitle() # False

开始

starstwith()

查是否以指定字符串开头,是返回True,否返回False,如果有下标,则在指定范围内检查
字符串序列.startswith(子串,开始位置下标,结束位置下标)

"you and me and he".startswith("you") # True
"you and me and he".startswith("and") # False
"you and me and he".startswith("and",4,) # True
endstwith()

查是否以指定字符串结尾,是返回True,否返回False,如果有下标,则在指定范围内检查
字符串序列.endswith(子串,开始位置下标,结束位置下标)

"you and me and he".endswith("he") # True
"you and me and he".endswith("and") # False
"you and me and he".endswith("and",4,) # True

列表

列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现
[数据1,数据2,数据3,…]

坐标

坐标可以精确找到序列中的字符

l = ["a","b","c"]
l[0] # 'a'
l[-1] # 'c'

切片

截取序列中的一部分
序列名[开始位置下标(默认0):结束位置下标(默认最后位置+1):步长(默认1)] 不包含结束位置,步长可以为负数,表示倒序取,字符串、列表、元组都支持切片操作

l = ["a",'b',"c","d","e","f","g"]
l[:] # 'a', 'b', 'c', 'd', 'e', 'f', 'g'] 不写开头表示从头取,不写结尾表示取到最后
l[2:5] # ['c', 'd', 'e']
l[::2] # ['a', 'c', 'e', 'g']
l[::-1] # ['g', 'f', 'e', 'd', 'c', 'b', 'a'] 步长负数表示倒序取
l[-5:-1:-1] # [] 方向和步长冲突,取不到数据

append()

列表结尾追加数据
列表序列.append(数据)

l = []
l.append("a")
l # ['a']
l.append(["b","c"])
l # ['a', ['b', 'c']]

insert()

指定位置新增数据
列表序列.insert(位置下标,数据)

l = ["a","b","c"]
l.insert(0,"x")
['x', 'a', 'b', 'c']

extend()

列表结尾追加数据
列表序列.extend (数据)

l = []
l.extend("a")
l # ['a']
l.extend(["b","c"])
l # ['a', 'b', 'c'] extend()追加数据时一个序列,会把序列拆开,逐一追加到列表

del()

删除列表或者删除列表中指定坐标的数据

l = ["a","b","c"]
del l[1]
l # ['a', 'c']
del l
l # NameError: name 'l' is not defined

pop()

删除指定下标的数据(默认最后一个),并返回该数据

l = ["a","b","c"]
l.pop() # 'c'
l # ['a', 'b']
l.pop(0) # 'a'
l # ['b']

remove()

移除列表中某个数据的第一个匹配项,如果有2个,只移除第一个

l = ["a","b","a","c"]
l.remove("b")
l # ['a', 'a', 'c']
l.remove("a") # 如果有2个匹配项,只移除第一个
l # ['a', 'c']

clear()

清空列表

l = ["a","b","c"]
l.clear()
l # []

修改指定坐标数据

l = ["a","b","c"]
l[1] = "x"
l # ['a', 'x', 'c']

复制

copy()

复制列表,工作中一般删除之前要复制一份

 l = ["a","b","c"]
 l.copy() # ['a', 'b', 'c']

排序

sort()

排序:升序、降序,原地排序,会改变原来的列表
列表序列.sort(key=None,reverse=False)
reverse表示排序规则 reverse=Ture降序, 默认reverse=False升序

l = ["b","a","c"]
l.sort()
l # ['a', 'b', 'c']
l.sort(reverse=True
l # ['c', 'b', 'a']

sorted()

排序。有返回值,生成排序后的新列表

l = ["b","a","c"]
sorted(l) # ['a', 'b', 'c']

reverse()

逆置,原地反转

l = ["a","b","c"]
l.reverse()
l # ['c', 'b', 'a']

index()

返回指定数据所在位置的下标,如果不存在报错
列表序列.index(数据,开始位置下标,结束位置下标)

l = ["a","b","c"]
l.index("a") # 0
l.index("d") # ValueError: 'd' is not in list
l.index("b",1,2) # 1

循环遍历

直接遍历

l = ["a","b","c"]
for i in l: 
    print(i,end=" ") # a b c

坐标遍历

l = ["a","b","c"]
for i in range(len(l)):
    print(l[i],end=" ") # a b c

嵌套

列表的嵌套指的是列表中元素也是列表

l = ["a","b",["c","d"]]
l[2] # ['c', 'd']
l[2][1] # 'd'

元组

元组:可以存储多个数据,元组内的数据不能修改
定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型
定义元组只有一个数据,数据后面也要添加逗号,否则数据类型为那一个数据的类型

t=(1,2)
type(t) # <class 'tuple'>
t1=(1)
type(t1) # <class 'int'> 
t2 = (1,)
type(t2) # <class 'tuple'>

元组原则上不能更改,如果元组中有可变类型数据,如列表,那么列表中的数据可以更改

t = ("a","b",["c","d"])
t[2][0] = "x"
t # ('a', 'b', ['x', 'd'])

index()

查找某个数据,如果数据存在返回对应下标,否则报错

t = ("a","b","c")
t.index("a") # 0

字典

大括号,键值对形式出现,键值对之间用逗号隔开
创建空字典 {} 或者dict()

d = {1:"a",2:"b"}
type(d) # <class 'dict'>
d1={}
type(d1) # <class 'dict'>
d2=dict()
type(d2) <class 'dict'>
d3 = dict(a=1,b=2)
d3 # {'a': 1, 'b': 2}
d4 = dict([(1,"a"),(2,"b")])
d4 # {1: 'a', 2: 'b'}

fromkeys()

fromkeys(seq,value)
函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值

d = d.fromkeys([1,2,3])
d # {1: None, 2: None, 3: None}
d = d.fromkeys([1,2,3],"x")
d # {1: 'x', 2: 'x', 3: 'x'}

增/改

字典序列[key]=值

如果key存在,会修改key的值,如果不存在新增此键值对,字典为可变类型

  d = {1:"a",2:"b"}
  d[1]="x"
  d # {1: 'x', 2: 'b'}
  d[3] = "c"
  d # {1: 'x', 2: 'b', 3: 'c'}

update()

函数把字典dict2的键/值对更新到dict里

d = {1:"a",2:"b"}
d1 = {3:"c"}
d.update(d1)
d # {1: 'a', 2: 'b', 3: 'c'}

del

删除字典或删除字典中指定键值对

d = {1:"a",2:"b"}
del d[2]
d # {1: 'a'}
del d
d # NameError: name 'd' is not defined

pop()

删除字典给定键 key 及对应的值,返回值为被删除的值。key 值必须给出。

d = {1:"a",2:"b"}
d.pop(1) # 'a'
d # {2: 'b'}

popitem()

方法返回并删除字典中的最后一对键和值

d = {1:"a",2:"b"}
d.popitem() # (2, 'b')
d # {1: 'a'}

clear()

函数用于删除字典内所有元素。

d = {1:"a",2:"b"}
d.clear()
d # {}

key查找

d = {1:"a",2:"b"}
d[1] # 'a'

get()

d = {1:"a",2:"b"}
d.get(1) # 'a'

遍历

遍历字典的key

d = {1:"a",2:"b"}
for key in d.keys():
    print(key,end=" ") # 1 2

遍历字典的value

d = {1:"a",2:"b"}
for value in d.values():
    print(value,end=" ") # a b

遍历字典的item

d = {1:"a",2:"b"}
for item in d.items():
    print(item,end=" ") # (1, 'a') (2, 'b')

遍历字典的key,value

d = {1:"a",2:"b"}
for key,value in d.items():
    print(f"{key}={value}",end=" ") # 1=a 2=b

集合

集合是无序不重复序列
创建集合使用{}或者set(),创建空集合只能使用set,因为{}用来创建字典

s= {1,1,2,2,3}
s # {1, 2, 3}
s1=set()
type(s1) # <class 'set'>

add()

向集合增加单个数据,只能增加单个数据,增加多个会报错
集合是可变类型,集合数据没有顺序,不能使用下标
集合有去重功能,如果增加的数据已存在,则不进行操作

s = {1,2,3}
s.add(1)
s # {1, 2, 3}
s.add(4)
s # {1, 2, 3, 4}

update()

向集合增加数据序列(集合、列表、字符串),多个数据,只能增加序列,不能增加单个 数据

s = {1,2,3}
s.update("45")
s # {1, 2, 3, '4', '5'}
s.update([6])
s # {1, 2, 3, 6, '4', '5'}

discard()

删除集合中指定数据,如果不存在也不报错

s = {1,2,3}
s.discard(1)
s # {2, 3}
s.discard(1)
s # {2, 3}

remove()

删除集合中指定数据,如果不存在就报错

s = {1,2,3}
s.remove(1)
s # {2, 3}
s.remove(1) # KeyError: 1

pop()

随机删除集合中数据,并返回该数据

s = {1,2,3}
s.pop() # 1
s #{2, 3}

公共操作

运算

+

合并 支持字符串、列表、元组

"a" + "b" # 'ab'
[1,2]+[3,4] # [1, 2, 3, 4]
(1,2) + (3,4) # (1, 2, 3, 4)

*

复制 支持字符串、列表、元组

"a"*3 # 'aaa'
[1,2] * 3 # [1, 2, 1, 2, 1, 2]
(1,2) * 3 # (1, 2, 1, 2, 1, 2)

判断

in

元素是否存在 支持字符串、列表、元组、集合、字典的key

"a" in "abc" # True
"a" in ["a","b"] # True
"a" in ("a","b") # True
"a" in {"a","b"} # True
"a" in {"a":1,"b":2} # True

not in

元素是否不存在 支持字符串、列表、元组、集合、字典的key

"a" not in "abc" # False
"a" not in ["a","b"] # False
"a" not in ("a","b") # False
"a" not in {"a","b"} # False
"a" not in {"a":1,"b":2} # False

方法

len()

统计器数据个数,支持字符串、列表、元组、集合、字典

len("abc") # 3
len([1,2,3]) # 3
len((1,2,3)) # 3
len({1,2,3}) # 3
len({1:2,3:4}) # 2

count()

统计序列中元素的个数,支持字符串、列表、元组

"aabc".count("a") # 2
["a","a","b","c"].count("a") # 2
("a","a","b","c").count("a") # 2

max()

返回容器中元素最大值 支持字符串、列表、元组、集合

max("123") # '3'
max([1,2,3]) # 3
max((1,2,3)) # 3
max({1,2,3}) # 3

min()

返回容器中元素最小值 支持字符串、列表、元组、集合

min("123") # '1'
min([1,2,3]) # 1
min((1,2,3)) # 1
min({1,2,3}) # 1

类型转换

list()

转列表

list("abc") # ['a', 'b', 'c']
list(("a","b","c")) # ['a', 'b', 'c']
list({"a","b","c"}) # ['a', 'b', 'c']

tuple()

转元组

tuple("abc") # ('a', 'b', 'c')
tuple(["a","b","c"]) # ('a', 'b', 'c')
tuple({"a","b","c"}) # ('a', 'b', 'c')

set()

转集合

set("abc") # {'a', 'c', 'b'}
set(["a","b","c"]) # {'a', 'c', 'b'}
set(("a","b","c")) # {'a', 'c', 'b'}

组包和拆包

组包

组包: 自动操作,当=右边有多个数据的时候,会自动包装成为元组

result = 1,2,3
result # (1, 2, 3)

拆包

变量数量 = 元素数量 会进行一一赋值

a,b = "12" # 字符串
a # 1
b # 2
a,b = [1,2] # 列表
a # 1
b # 2
a,b = (1,2) # 元组
a # 1
b # 2
a,b = {1,2} # 集合
a # 1
b # 2
a,b = {1:"x",2:"y"} # 字典拆包得到的是key
a # 1
b # 2

推导式

列表推导式

用一个表达式创建一个有规律的列表或控制一个有规律的列表,又叫列表生成式

l = [i for i in range(3)]
l # [0, 1, 2]

带if

l = [i for i in range(5) if i % 2==0]
l # [0, 2, 4]

多个for

l = [(i,j) for i in range(3) for j in range(3)]
l # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

字典推导式

快速合并列表为字典或提取字典中目标数据

d = {i:i**2 for i in range(1,3)}
d # {1: 1, 2: 4}
l1 = [1,2,3]
l2 = ["a","b","c"]
d = {l1[i]:l2[i] for i in range(len(l1))}
d # {1: 'a', 2: 'b', 3: 'c'}

带if

counts = {'MBP':268,'HP':125,'DELL':201,'Lenovo':199,'acer':99}
d = {key:value for key,value in counts.items() if value >= 200}
d # {'MBP': 268, 'DELL': 201}

集合推导式

l = [1,1,2]
s = {i**2 for i in l}
s # {1, 4}

带if

l = [1,1,2]
s = {i**2 for i in l if i >=2}
s # {4}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值