python常见的数据类型及其作用方法

title: “python数据类型及其常用方法”
date: 2020-04-21T10:15:44+08:00


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

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

  1. # append用于在列表末尾追加新的对象
  2. # list.append(obj)
  3. a = [1,2,3]
  4. print(a.append('4'))
  5. # the result : [1, 2, 3, '4']
  1. # extend方法可以在列表的末尾一次性追加另一个序列中的多个值
  2. a = [1,2,3]
  3. b = [4,5,6]
  4. a.extend(b)
  5. print(a)
  6. # the result :[1, 2, 3, 4, 5, 6]
  1. # insert方法用于将对象插入到列表中
  2. # list.insert(index, obj)
  3. a = [1,2,3]
  4. a.insert(0,'aa')
  5. print(a)
  6. # the result : ['aa', 1, 2, 3]
  1. # pop方法会移除列表中的一个元素(默认是最后一个),并且(返回)该元素的值,若索引溢出会报错
  2. # list.pop([index=-1])
  3. a = [1,2,3]
  4. print(a.pop())
  5. # the result : 3
  6. print(a)
  7. # the result : [1,2]
  1. # remove方法用于移除列表中某个值的第一个匹配项
  2. a = ['aa','bb','cc','aa']
  3. a.remove('aa')
  4. print(a)
  5. # the result : ['bb', 'cc', 'aa']
  1. # reverse方法将列表中的元素反向存放
  2. a = ['a','b','c']
  3. a.reverse()
  4. print(a)
  5. # the result : ['c', 'b', 'a']
  1. # sort方法用于在原位置对列表进行排序,意味着改变原来的列表,让其中的元素按一定顺序排列
  2. # list.sort(cmp=None, key=None, reverse=False)
  3. # cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
  4. # key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对 象中的一个元素来进行排序。
  5. # reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
  6. def takeSecond(elem):
  7. return elem[1]
  8. random = [(2, 2), (3, 4), (4, 1), (1, 3)]
  9. random.sort(key=takeSecond,reverse=True)
  10. print (random)
  11. # the result : [(3, 4), (1, 3), (2, 2), (4, 1)]
  1. # count方法统计某个元素在列表中出现的次数
  2. a = ['aa','bb','cc','aa','aa']
  3. print(a.count('aa'))
  4. # the result : 3
  1. # index函数用于从列表中找出某个值第一个匹配项的索引位置,匹配范围内没有则报错,需要注意的是end值为左闭右开区间
  2. # list.index(x[, start[, end]])
  3. a = [1,2,3,1]
  4. print(a.index(1))
  5. print(a.index(3,1,3))
  6. # the result : 0
  7. # the result : 2
  1. # 带索引的遍历
  2. # enumerate(sequence, [start=0])
  3. # sequence -- 一个序列、迭代器或其他可迭代对象。
  4. # start -- 下标起始位置,可选参数,默认为0。
  5. li = [11,22,33]
  6. for k,v in enumerate(li):
  7. print(k,v)
  8. # 0 11
  9. # 1 22
  10. # 2 33
  11. print(list(enumerate(li,8)))
  12. #[(8, 11), (9, 22), (10, 33)]
  1. #dict.fromkeys(seq[, value])
  2. seq = ('Google', 'Runoob', 'Taobao')
  3. dict = dict.fromkeys(seq,1)
  4. print(dict)
  5. # {'Google': 1, 'Runoob': 1, 'Taobao': 1}
  1. # 将两个列表组合成字典
  2. keys = ['a', 'b']
  3. values = [1, 2]
  4. print(dict(zip(keys,values)))
  5. # {'a': 1, 'b': 2}

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

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

  1. #考虑下面的股票名和价格映射字典:
  2. prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}
  3. #为了对字典值执行计算操作,通常需要使用zip()函数先将键和值反转过来.
  4. #下面是查找最小和最大股票价格和股票值的代码:
  5. min_price = min(zip(prices.values(), prices.keys()))
  6. # min_price is (10.75, 'FB')
  7. max_price = max(zip(prices.values(), prices.keys()))
  8. # max_price is (612.78, 'AAPL')
  9. #类似的,可以使用zip() 和sorted() 函数来排列字典数据:
  10. prices_sorted = sorted(zip(prices.values(), prices.keys()))
  11. # prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'),(45.23, 'ACME'), (205.55, 'IBM'),(612.78, 'AAPL')]
  12. 执行这些计算的时候,需要注意的是zip() 函数创建的是一个只能访问一次的迭代器。比如,下面的代码就会产生错误:
  13. prices_and_names = zip(prices.values(), prices.keys())
  14. print(min(prices_and_names)) # OK
  15. print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
  16. #字典值相同,键不同,比较值的大小
  17. prices = { 'AAA' : 45.23, 'ZZZ': 45.23 }
  18. min(zip(prices.values(), prices.keys()))
  19. #(45.23, 'AAA')
  20. max(zip(prices.values(), prices.keys()))
  21. #(45.23, 'ZZZ')
  1. # clear方法清除字典中所有的项,这是一个原地操作,所以无返回值(或则说返回None)
  2. d = {'name':"tom"}
  3. d.clear()
  4. print(d)
  5. #the result : {}
  1. # 删除字典给定键 key 及对应的值,返回值为被删除的值
  2. d = {'Tom':8777,'Jack':8888,'Fly':6666}
  3. v = d.pop('Tom')
  4. print(v)
  5. # 8777
  6. print(d)
  7. # {'Jack': 8888, 'Fly': 6666}
  1. # update方法可以利用一个字典项更新另一个字典,提供的字典中的项会被添加到旧的字典中,如有相同的键则会被覆盖
  2. d = {'Tom':8777,'Jack':8888,'Fly':6666}
  3. a = {'Tom':110,'Test':119}
  4. d.update(a)
  5. print(d)
  6. #the result :{'Fly': 6666, 'Test': 119, 'Jack': 8888, 'Tom': 110}
  1. # get方法是个更宽松的访问字典的方法,如果试图访问字典中不存在的项时不会报错,仅会返回:None
  2. d = {'Tom':8777,'Jack':8888,'Fly':6666}
  3. print(d.get('Tom'))
  4. #the result :8777
  5. print(d.get('not_exist'))
  6. #the result:None
  1. # dict.items()返回可遍历的(键, 值) 元组数组。
  2. dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com'}
  3. print (dict.items())
  4. # dict_items([('Google', 'www.google.com'), ('Runoob', 'www.runoob.com')])

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

  1. for k,v in d.items():
  2. print(k,v)
  3. for k in d.values():
  4. print(k)
  5. for k in d.keys():
  6. print(k)

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

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

  1. print(set(list_1))
  2. # {1, 2, 3, 4, 5}
  3. print(list_1)
  4. # [1, 2, 3, 4, 5, 1, 2]
  1. print(set(list_1).intersection(set(list_2)))
  2. # {4, 5}
  1. print(set(list_1).union(set(list_2)))
  2. # {1, 2, 3, 4, 5, 6, 7, 8}
  1. # 在list_1中有在list_2中没有
  2. print(set(list_1).difference(set(list_2)))
  3. # {1, 2, 3}
  1. # find方法可以在一个较长的字符串中查找子串,他返回子串所在位置的最左端索引,如果没有找到则返回-1
  2. a = 'abcdefghijk'
  3. print(a.find('abc'))
  4. #the result : 0
  5. print(a.find('abc',10,100))
  6. #the result : -1 指定查找的起始和结束查找位置
  7. # rfind方法类似,是从后往前找
  1. # 返回一个字符串,是split方法的逆方法,用来连接序列中的元素,并且需要被连接的元素都必须是字符串。
  2. a = ['1','2','3']
  3. print('+'.join(a))
  4. #the result : 1+2+3
  1. # split是join的逆方法,用来将字符串分割成序列
  2. print('1+2+3+4'.split('+'))
  3. #the result : ['1', '2', '3', '4']
  1. # strip 方法返回去除首位空格(不包括内部)的字符串
  2. print(" test test ".strip())
  3. #the result :“test test”
  1. # replace方法返回某字符串所有匹配项均被替换之后得到字符串
  2. print("This is a test".replace('is','is_test'))
  3. #the result : This_test is_test a test

版权声明:本文为fairytalk原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/fairytalk/p/13152744.html