首页 技术 正文
技术 2022年11月9日
0 收藏 594 点赞 4,518 浏览 4728 个字

title: "python数据类型及其常用方法"

date: 2020-04-21T10:15:44+08:00


可变数据类型:允许变量的值发生变化,即如果对变量进行append、+=等这种操作后,只是改变了变量的值,而不会新建一个对象,变量引用的对象的地址也不会变化,不过对于相同的值的不同对象,在内存中则会存在不同的对象,即每个对象都有自己的地址,相当于内存中对于同值的对象保存了多份,这里不存在引用计数,是实实在在的对象.如 **list,dict,set **

不可变数据类型:不允许变量的值发生变化,如果改变了变量的值,相当于是新建了一个对象,而对于相同的值的对象,在内存中则只有一个对象,内部会有一个引用计数来记录有多少个变量引用这个对象。如 **Number,String, Tuple **

list常用方法

append()
# append用于在列表末尾追加新的对象
# list.append(obj)
a = [1,2,3]
print(a.append('4'))
# the result : [1, 2, 3, '4']
extend()
# extend方法可以在列表的末尾一次性追加另一个序列中的多个值
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
# the result :[1, 2, 3, 4, 5, 6]
insert()
# insert方法用于将对象插入到列表中
# list.insert(index, obj)
a = [1,2,3]
a.insert(0,'aa')
print(a)
# the result : ['aa', 1, 2, 3]

pop()
# pop方法会移除列表中的一个元素(默认是最后一个),并且(返回)该元素的值,若索引溢出会报错
# list.pop([index=-1])
a = [1,2,3]
print(a.pop())
# the result : 3
print(a)
# the result : [1,2]
remove()
# remove方法用于移除列表中某个值的第一个匹配项
a = ['aa','bb','cc','aa']
a.remove('aa')
print(a)
# the result : ['bb', 'cc', 'aa']

reverse()
# reverse方法将列表中的元素反向存放
a = ['a','b','c']
a.reverse()
print(a)
# the result : ['c', 'b', 'a']
sort()
# sort方法用于在原位置对列表进行排序,意味着改变原来的列表,让其中的元素按一定顺序排列
# list.sort(cmp=None, key=None, reverse=False)
# cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。def takeSecond(elem):
return elem[1]
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond,reverse=True)
print (random)
# the result : [(3, 4), (1, 3), (2, 2), (4, 1)]

count()
# count方法统计某个元素在列表中出现的次数
a = ['aa','bb','cc','aa','aa']
print(a.count('aa'))
# the result : 3
index()
# index函数用于从列表中找出某个值第一个匹配项的索引位置,匹配范围内没有则报错,需要注意的是end值为左闭右开区间
# list.index(x[, start[, end]])a = [1,2,3,1]
print(a.index(1))
print(a.index(3,1,3))
# the result : 0
# the result : 2
enumerate()
# 带索引的遍历
# enumerate(sequence, [start=0])
# sequence -- 一个序列、迭代器或其他可迭代对象。
# start -- 下标起始位置,可选参数,默认为0。li = [11,22,33]
for k,v in enumerate(li):
print(k,v)
# 0 11
# 1 22
# 2 33print(list(enumerate(li,8)))
#[(8, 11), (9, 22), (10, 33)]

Dict常用方法

fromkeys()
#dict.fromkeys(seq[, value])
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq,1)
print(dict)
# {'Google': 1, 'Runoob': 1, 'Taobao': 1}
zip()
# 将两个列表组合成字典
keys = ['a', 'b']
values = [1, 2]
print(dict(zip(keys,values)))
# {'a': 1, 'b': 2}

相反,zip()作用于字典,会创建一个**只能访问一次的迭代器 **

可以思考–怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)?

#考虑下面的股票名和价格映射字典:
prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}
#为了对字典值执行计算操作,通常需要使用zip()函数先将键和值反转过来.
#下面是查找最小和最大股票价格和股票值的代码:
min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')#类似的,可以使用zip() 和sorted() 函数来排列字典数据:
prices_sorted = sorted(zip(prices.values(), prices.keys()))
# prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'),(45.23, 'ACME'), (205.55, 'IBM'),(612.78, 'AAPL')]执行这些计算的时候,需要注意的是zip() 函数创建的是一个只能访问一次的迭代器。比如,下面的代码就会产生错误:prices_and_names = zip(prices.values(), prices.keys())
print(min(prices_and_names)) # OK
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence#字典值相同,键不同,比较值的大小prices = { 'AAA' : 45.23, 'ZZZ': 45.23 }
min(zip(prices.values(), prices.keys()))
#(45.23, 'AAA')
max(zip(prices.values(), prices.keys()))
#(45.23, 'ZZZ')

clear()
# clear方法清除字典中所有的项,这是一个原地操作,所以无返回值(或则说返回None)
d = {'name':"tom"}
d.clear()
print(d)
#the result : {}

pop()
# 删除字典给定键 key 及对应的值,返回值为被删除的值
d = {'Tom':8777,'Jack':8888,'Fly':6666}
v = d.pop('Tom')
print(v)
# 8777
print(d)
# {'Jack': 8888, 'Fly': 6666}
update()
# update方法可以利用一个字典项更新另一个字典,提供的字典中的项会被添加到旧的字典中,如有相同的键则会被覆盖
d = {'Tom':8777,'Jack':8888,'Fly':6666}
a = {'Tom':110,'Test':119}
d.update(a)
print(d)
#the result :{'Fly': 6666, 'Test': 119, 'Jack': 8888, 'Tom': 110}

get()
# get方法是个更宽松的访问字典的方法,如果试图访问字典中不存在的项时不会报错,仅会返回:None
d = {'Tom':8777,'Jack':8888,'Fly':6666}
print(d.get('Tom'))
#the result :8777
print(d.get('not_exist'))
#the result:None
item()
# dict.items()返回可遍历的(键, 值) 元组数组。
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com'}
print (dict.items())
# dict_items([('Google', 'www.google.com'), ('Runoob', 'www.runoob.com')])

由此引出遍历字典的三种方法

for k,v in d.items():
print(k,v)
for k in d.values():
print(k)
for k in d.keys():
print(k)

set常用方法

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

list_2 = [4,5,6,7,8]

去重
print(set(list_1))
# {1, 2, 3, 4, 5}
print(list_1)
# [1, 2, 3, 4, 5, 1, 2]
交集
print(set(list_1).intersection(set(list_2)))
# {4, 5}
并集
print(set(list_1).union(set(list_2)))
# {1, 2, 3, 4, 5, 6, 7, 8}
差集
# 在list_1中有在list_2中没有
print(set(list_1).difference(set(list_2)))
# {1, 2, 3}

str常用方法(不可变)

find(),rfind()
# find方法可以在一个较长的字符串中查找子串,他返回子串所在位置的最左端索引,如果没有找到则返回-1
a = 'abcdefghijk'
print(a.find('abc'))
#the result : 0
print(a.find('abc',10,100))
#the result : -1 指定查找的起始和结束查找位置# rfind方法类似,是从后往前找
join()
# 返回一个字符串,是split方法的逆方法,用来连接序列中的元素,并且需要被连接的元素都必须是字符串。
a = ['1','2','3']
print('+'.join(a))
#the result : 1+2+3
split()
# split是join的逆方法,用来将字符串分割成序列
print('1+2+3+4'.split('+'))
#the result : ['1', '2', '3', '4']
strip()
# strip 方法返回去除首位空格(不包括内部)的字符串
print(" test test ".strip())
#the result :“test test”
replace()
# replace方法返回某字符串所有匹配项均被替换之后得到字符串
print("This is a test".replace('is','is_test'))
#the result : This_test is_test a test
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,497
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298