Python-基本数据类型的常用内置方法
一、数字类型
-
int类型 定义: age = 20
类型转换: ? (1)纯数字的字符串转成int
res = int('100111')
print(res, type(res))
? (2)十进制转成其他进制
11 - > 1011
1011-> 8 + 2 + 1
print(bin(11))
print(oct(11))
print(hex(11))
print(hex(123))
? (3)其他进制转十进制
print(int('0b1011',2))
print(int('0o13',8))
print(int('0xb',16))
-
float类型 定义: salary = 333.3
类型转换: res = float("3.1")
print(res, type(res))
int与float没有需要掌握的内置方法,它们的使用就是数学运算和比较运算。
二、字符串类型(重要)
定义:
msg = 'hello python'
类型转换:str可以把任意其他类型都转成字符串
res = str({'a': 1})
print(res, type(res))
内置方法:Python的字符串是不可变类型,所以通过内置方法得到的字符串并不是改变了原字符串,而是产生了新的字符串。
1. 按索引取值(正向取+反向取) :只能取不能改
msg = 'hello world'
print(msg[0])
print(msg[5])
print(msg[-1])
msg[0] = 'H'
2. 切片:索引的拓展应用,从一个大字符串中 拷贝 出一个子字符串
msg = 'hello world'
res = msg[0:5]
print(res)
print(msg)
res = msg[0:5:2]
print(res)
res = msg[5:0:-1]
print(res)
print(msg[0:5:-1])
print(msg[5:0])
msg = 'hello world'
res = msg[::-1]
print(res)
msg = 'hello world'
res0 = msg[:5]
print(res0)
res1 = msg[0:]
print(res1)
res2 = msg[:5:-1]
print(res2)
res3 = msg[4::-1]
print(res3)
res4 = msg[4:0:-1]
print(res4)
msg1 = 'hello:world:<>:19[]==123'
msg2 = msg1[:]
print(msg1, id(msg1))
print(msg2, id(msg2))
3. 长度len
msg = 'hello world'
print(len(msg))
4. 成员运算in和not in
print("hello" in "hello world")
print("hello" not in "hello world")
print(not "hello" in "hello world")
5. 移除字符串左右两侧的符号strip
msg = ' abcd '
res = msg.strip()
print(msg)
print(res)
msg = '****abcd****'
print(msg.strip('*'))
msg = '****a*****bcd****'
print(msg.strip('*'))
msg = '**/*===-**abcd**---/-=()**'
print(msg.strip('*/-=()'))
inp_user = input('your name>>: ').strip()
inp_pwd = input('your password>>: ').strip()
if inp_user == 'admin' and inp_pwd == '123':
print('登录成功')
else:
print('账号密码错误')
6. 切分split:把一个字符串按照某种分隔符进行切分,得到一个列表
info = 'Python JavaScript Golang'
res = info.split()
print(res)
info = 'Python、JavaScript、Golang'
res = info.split('、')
print(res)
info = 'Python:JavaScript:Golang'
res = info.split(':', 1)
print(res)
7. 循环
info = 'Python:JavaScript:Golang'
for x in info:
print(x, end=',')
8. strip,lstrip,rstrip
msg = '***abcd****'
print(msg.strip('*'))
print(msg.lstrip('*'))
print(msg.rstrip('*'))
9. lower,upper
msg = 'AbbbCCCC'
print(msg.lower())
print(msg.upper())
10. startswith,endswith
print("alex is sb".startswith("alex"))
print("alex is sb".endswith('sb'))
11. format
(1)按位置传值:
res = '我的名字是 {} 我的年龄是 {}'.format('JL',19)
print(res)
res='我的名字是 {0}{0}{0} 我的年龄是 {1}{1}'.format('JL',19)
print(res)
(2)打破位置的限制,按照 key = value 传值:
res="我的名字是 {name} 我的年龄是 {age}".format(age=19,name='JL')
print(res)
12. split,rsplit:将字符串切成列表
? split见上方“6.切分split”
info = "Python:JavaScript:Golang"
print(info.split(':', 1))
print(info.rsplit(':', 1))
13. join:把列表拼接成字符串
l = ['Python', 'JavaScript', 'Golang']
res0 = l[0] + ":" + l[1] + ":" + l[2]
print(res0)
res = ":".join(l)
print(res)
l = [1, "2", 'aaa']
res = ":".join(l)
14. replace
msg = "you can you up no can no bb"
print(msg.replace("you", "YOU", ))
print(msg.replace("you", "YOU", 1))
15. isdigit
print('123'.isdigit())
print('12.3'.isdigit())
age = input('请输入你的年龄:').strip()
if age.isdigit():
age = int(age)
if age > 19:
print('猜大了')
elif age < 19:
print('猜小了')
else:
print('才最了')
else:
print('必须输入数字,傻子')
16. find,rfind,index,rindex,count
msg = 'hello world of python '
print(msg.find('e'))
print(msg.find('py'))
print(msg.index('o'))
print(msg.index('of'))
msg = 'hello world of python '
print(msg.find('xxx'))
print(msg.index('xxx'))
msg = 'Hello python hahaha,Bye java oh my god!'
print(msg.count('a'))
print(msg.count('ha'))
17. center,ljust,rjust,zfill
print('jl'.center(12, '*'))
print('jl'.ljust(15, '*'))
print('jl'.rjust(10, '*'))
print('jl'.zfill(10))
18. expandtabs
msg = 'hello\tworld'
print(msg.expandtabs(2))
19. captalize,swapcase,title
print("hello world jl".capitalize())
print("Hello WorLd JL".swapcase())
print("hello world jL".title())
20. is数字系列
num1 = b'4'
num2 = u'4'
num3 = '四'
num4 = 'Ⅳ'
print(num1.isdigit())
print(num2.isdigit())
print(num3.isdigit())
print(num4.isdigit())
print(num2.isnumeric())
print(num3.isnumeric())
print(num4.isnumeric())
print(num2.isdecimal())
print(num3.isdecimal())
print(num4.isdecimal())
21. is其他
print('abc'.islower())
print('ABC'.isupper())
print('Hello World'.istitle())
print('123123aadsf'.isalnum())
print('ad'.isalpha())
print(' '.isspace())
print('print'.isidentifier())
print('age_of_tony'.isidentifier())
print('1age_of_tony'.isidentifier())
三、列表类型(有序)
作用:按位置存放多个值
类型转换:但凡能够被for循环遍历的类型都可以当做参数传给list()转成列表
res = list('hello')
print(res)
res = list({'k1': 111, 'k2': 222, 'k3': 3333})
print(res)
内置方法
-
按索引存取值(正向存取+反向存取):即可以取也可以改 l = [111, 'world', 'hello']
print(l[0])
print(l[-1])
l[0] = 222
print(l)
l[3] = 333
-
切片(顾头不顾尾,步长) l = [111, 'world', 'hello', 'a', 'b', 'c', 'd', [1, 2, 3]]
print(l[0:3])
print(l[0:5:2])
print(l[0:len(l)])
print(l[:])
new_l = l[:]
print(id(l))
print(id(new_l))
l[-1][0] = 1111111
print(l)
print(new_l)
print(l[::-1])
-
长度 print(len([1, 2, 3]))
-
成员运算in和not in print('aaa' in ['aaa', 1, 2])
print(1 in ['aaa', 1, 2])
print(3 not in ['aaa', 1, 2])
-
往列表中添加值 追加 l = [111, '222', 'hello']
l.append(3333)
print(l)
l.append(4444)
print(l)
指定位置插入值 l = [111, 'JavaScript', 'Golang']
l.insert(0, 'Python')
print(l)
l.insert(0, 1)
print(l)
l.extend()
new_l = [1, 2, 3]
l = [111, 'Python', 'JavaScript']
l.append(new_l)
print(l)
new_l = [1, 2, 3]
l = [111, 'Python', 'JavaScript']
for item in new_l:
l.append(item)
print(l)
l.extend(new_l)
print(l)
l.extend('abc')
print(l)
-
删除 方式一:通用的删除方法,只是单纯的删除、没有返回值 l = [111, 'world', 'hello']
del l[1]
print(l)
方式二:l.pop()根据索引删除,会返回删除的值 l = [111, 'world', 'hello']
l.pop()
l.pop()
print(l)
l = [111, 'world', 'hello']
res = l.pop(1)
print(l)
print(res)
方式三:l.remove()根据元素删除,返回None(主观上相当于无返回值) l = [111, 'world', [1, 2, 3], 'hello']
l.remove([1, 2, 3])
print(l)
res = l.remove('world')
print(res)
print(l)
-
循环 l = [1, 'aaa', 'bbb']
for x in l:
print(x)
-
l.copy
见“Python学习_ 基础 _05_if条件判断、列表的深浅copy:三、2. a. 浅copy”
-
l.count()
l = [1, 'aaa', 'bbb', 'aaa', 'aaa']
print(l.count('aaa'))
-
l.index()
l = [1, 'aaa', 'bbb', 'aaa', 'aaa']
print(l.index('aaa'))
print(l.index('aaaaaaaaa'))
-
l.clear()
l = [1, 'aaa', 'bbb', 'aaa', 'aaa']
l.clear()
print(l)
-
l.reverse():不是排序,而是将列表倒过来(反转) l = [1, 'PY', 'JS', 'GO']
l.reverse()
print(l)
-
l.sort(): 列表内元素必须是同种类型才可以排序,不然会报错 l = [11, -3, 9, 2, 3.1]
l.sort()
print(l)
l.sort(reverse=True)
print(l)
l = ['c', 'e', 'a']
l.sort()
print(l)
字符串可以比大小,按照对应的位置的字符依次pk,直到比出胜负。 字符的大小是按照ASCI码表的先后顺序加以区别,表中排在后面的字符大于前面的。 print('a' > 'b')
print('abz' > 'abcdefg')
列表也可以比大小,原理同字符串一样依次pk,但是对应位置的元素必须是同种类型。 l1 = [1, 'abc', 'zaa']
l2 = [1, 'abc', 'zb']
print(l1 < l2)
列表实现队列与堆栈
-
队列:FIFO(First In, First Out),先进先出 l=[]
l.append('first')
l.append('second')
l.append('third')
print(l)
print(l.pop(0))
print(l.pop(0))
print(l.pop(0))
-
堆栈:LIFO(Last In, First Out),后进先出 l=[]
l.append('first')
l.append('second')
l.append('third')
print(l)
print(l.pop())
print(l.pop())
print(l.pop())
四、元组类型(就是一个“不可变的列表”,有序,属于不可变类型)
作用:按照索引/位置存放多个值,只用于读不用于改
定义:( )内用逗号分隔开多个任意类型的元素j
t = (1, 1.3, 'aa')
print(t, type(t))
t = (10,)
print(t, type(t))
x = (10)
print(x, type(x))
t = (1, 1.3, 'aa')
t = (1, [11, 22])
print(id(t[0]), id(t[1]))
t[1][0] = 11111111111111111
print(t)
print(id(t[0]), id(t[1]))
类型转换:
print(tuple('hello'))
print(tuple([1, 2, 3]))
print(tuple({'a1': 111, 'a2': 333}))
内置方法:
-
按索引取值(正向取+反向取):只能取 t = ('aa', 'bbb', 'cc')
print(t[0])
print(t[-1])
-
切片(顾头不顾尾,步长)(切片是一种拷贝操作) t = ('aa', 'bbb', 'cc', 'dd', 'eee')
print(t[0:3])
print(t[::-1])
-
长度 t = ('aa', 'bbb', 'cc', 'dd', 'eee')
print(len(t))
-
成员运算in和not in t = ('aa', 'bbb', 'cc', 'dd', 'eee')
print('aa' in t)
-
循环 t = ('aa', 'bbb', 'cc', 'dd', 'eee')
for x in t:
print(x)
-
index() t = (2, 3, 111, 111, 111, 111)
print(t.index(111))
-
count() t = (2, 3, 111, 111, 111, 111)
print(t.count(111))
五、字典类型(无序)
定义:{ }内用逗号分隔开多个 key:value,其中 value 可以使任意类型,但是 key 必须是不可变类型,且不能重复。
造字典的方式一:
d = {'k1': 111, (1, 2, 3): 222}
print(d['k1'])
print(d[(1, 2, 3)])
print(type(d))
d = {}
print(d, type(d))
造字典的方式二:
d = dict(x=1, y=2, z=3)
print(d, type(d))
造字典的方式三:快速初始化一个字典
keys=['name','age','gender']
d={}.fromkeys(keys,None)
print(d)
keys = ['a', 'b', 'c', 'd']
d = {}
d = d.fromkeys(keys, 10)
print(d, '\n', id(d['a']), id(d['b']), id(d['c']))
d = d.fromkeys(keys, '字母')
print(d, '\n', id(d['a']), id(d['b']), id(d['c']))
d = d.fromkeys(keys, [1, 2, 3, 4])
d['a'][0] = 99
print(d)
数据类型转换
info = [
['name', '李白'],
('age', 18),
['gender', 'male']
]
d = {}
for x in info:
d[x[0]] = x[1]
print(d)
d = {}
for k, v in info:
d[k] = v
print(d)
res = dict(info)
print(res)
内置方法
-
按key存取值:可存可取 d = {'k1': 111}
d['k1'] = 222
d['k2'] = 3333
print(d)
-
长度len d = {'k1': 111, 'k2': 2222, 'k1': 3333, 'k1': 4444}
print(d)
print(len(d))
-
成员运算in和not in:根据key d = {'k1': 111, 'k2': 2222}
print('k1' in d)
print(111 in d)
-
删除 4.1 通用删除 d = {'k1': 111, 'k2': 2222}
del d['k1']
print(d)
4.2 pop删除:根据key删除元素,返回删除key对应的那个value值 d = {'k1': 111, 'k2': 2222}
res = d.pop('k2')
print(d)
print(res)
4.3 popitem删除:随机删除(不是从末尾删除,因为字典无序),返回元组(删除的key,删除的value) d = {'k1': 111, 'k2': 2222}
res = d.popitem()
print(d)
print(res)
-
键keys(),值values(),键值对items() =>在python3中得到的是老母鸡(为了节省空间) '''
在python2中:
d.keys()得到的是一个由字典全部key组成的列表;
d.values()得到的是一个由字典全部key的值(value)组成的列表;
d.items()得到的是一个由字典(key,value)组成的一个个元组所组成的列表。
>>> d={'k1':111,'k2':2222}
>>>
>>> d.keys()
['k2', 'k1']
>>> d.values()
[2222, 111]
>>> d.items()
[('k2', 2222), ('k1', 111)]
>>>
'''
d = {'k1': 111, 'k2': 2222}
print(d.keys())
print(d.values())
print(d.items())
? 让老母鸡下蛋的方法看下面“6. for循环”
-
for循环 d = {'k1': 111, 'k2': 2222}
for k in d:
print(k)
for v in d.values():
print(v)
for item in d.items():
print(item)
for k, v in d.items():
print(k, v)
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
-
d.clear()(清空字典,结果为 { } ) -
d.copy()(相当于浅拷贝) -
d.update() d = {'k1': 111, 'k2': 2222}
d.update({'k2': 222, 'k3': 333, 'k1': 88888})
print(d)
-
d.get():根据key取值,容错性好 d = {'k1': 111, 'k2': 2222}
print(d.get('k1'))
print(d.get('k3'))
d = {'k1': 111, 'k2': 2222}
res0 = d.get('k1', '空空如也')
res1 = d.get('k3', '空空如也')
print(res0)
print(res1)
-
d.setdefault():有则不改,无则添加
info = {}
if 'name' in info:
pass
else:
info['name'] = 'Python'
print(info)
info = {'name': 'JS'}
res = info.setdefault('name', 'PY')
print(res)
print(info)
info = {}
res = info.setdefault('name', 'GO')
print(res)
print(info)
六、集合类型
? 在学习集合类型之前,先思考一个简单的问题,怎样得到具有重合元素的两个列表的交集(重合)部分?且得到的部分用新列表表示。
friends1 = ["zero", "kevin", "jason", "egon"]
friends2 = ["Jy", "ricky", "jason", "egon"]
l = []
for x in friends1:
if x in friends2:
l.append(x)
print(l)
定义:
定义集合的三大注意:
- 集合内元素必须为不可变类型
- 集合内元素无序
- 集合内元素没有重复
s = {1, 2}
s = {1, 'a', 'z', 'b', 4, 7}
s = {1, 1, 1, 1, 1, 1, 'a', 'b'}
print(s)
s = {}
print(type(s))
s = set()
print(s, type(s))
类型转换:
res = set('hellolllll')
print(res)
print(set([1, 1, 1, 1, 1, 1]))
print(set({'k1': 1, 'k2': 2}))
内置方法:关系运算、去重
-
取交集:两者共同的好友 friends1 = {"zero", "kevin", "jason", "egon"}
friends2 = {"Jy", "ricky", "jason", "egon"}
res = friends1 & friends2
print(res)
-
取并集/合集:两者所有的好友 friends1 = {"zero", "kevin", "jason", "egon"}
friends2 = {"Jy", "ricky", "jason", "egon"}
print(friends1 | friends2)
-
取差集:取friends1独有的好友、取friends2独有的好友 friends1 = {"zero", "kevin", "jason", "egon"}
friends2 = {"Jy", "ricky", "jason", "egon"}
print(friends1 - friends2)
print(friends2 - friends1)
-
取对称差集: 求两个用户独有的好友们(即各种去掉共有的好友然后取并集) friends1 = {"zero", "kevin", "jason", "egon"}
friends2 = {"Jy", "ricky", "jason", "egon"}
print(friends1 ^ friends2)
-
父子集:包含与被包含的关系 s1 = {1, 2, 3}
s2 = {1, 2, 4}
print(s1 > s2)
print(s1 < s2)
s1 = {1, 2, 3}
s2 = {1, 2}
print(s1 > s2)
s1 = {1, 2, 3}
s2 = {1, 2, 3}
print(s1 == s2)
-
长度 s = {'a', 'b', 'c'}
print(len(s))
-
成员运算 s = {'a', 'b', 'c'}
print('a' in s)
print('b' not in s)
-
循环 s = {'a', 'b', 'c'}
for item in s:
print(item)
-
discard()
s = {1, 2, 3}
s.discard(3)
print(s)
-
update()
s = {1, 2, 3}
s.update({1,3,5})
print(s)
-
pop()
res = s.pop()
print(res)
-
add()
s.add(66)
print(s)
-
两个了解的方法 s = {1, 2, 3}
res = s.isdisjoint({3, 4, 5, 6})
print(res)
s.difference_update({3, 4, 5})
print(s)
集合可以去重,但是有局限性。
-
只能针对不可变类型去重 print(set([1,1,1,1,2]))
-
无法保证原来的顺序 l = [1, 'a', 'b', 'z', 1, 1, 1, 2]
l = list(set(l))
print(l)
利用循环对可变类型进行去重,而且保留顺序:
l = [
{'name': 'lili', 'age': 18, 'sex': 'male'},
{'name': 'jack', 'age': 73, 'sex': 'male'},
{'name': 'tom', 'age': 20, 'sex': 'female'},
{'name': 'lili', 'age': 18, 'sex': 'male'},
{'name': 'lili', 'age': 18, 'sex': 'male'},
]
new_l = []
for dic in l:
if dic not in new_l:
new_l.append(dic)
print(new_l)
总结:
本文参考文章:https://zhuanlan.zhihu.com/p/108793771
|