Python的组合数据类型
阅读原文时间:2023年07月10日阅读:4

"""
Python的组合类型:

序列类型:元素之间存在先后关系,可以通过索引来访问  
    列表:  
    元组:  
    字符串:

映射类型:用键值来表示数据  
    字典:

集合类型:元素是无序的,集合中不允许相同的元素存在,集合中的元素只能是整数、浮点数、字符串等基本数据类型  

"""

序列类型:支持成员关系操作符(in)、分片运算符[],序列中的元素也可以是序列类型

"""
序列的正向索引和反向索引
<- -9 -8 -7 -6 -5 -5 -4 -3 -2--- a b c d e f g h i ----1---2---3---4---5---6---7---8---9-->
x in s 如果x是序列s的元素,返回True,否则返回False
x not in s 如果x是序列s的元素,返回False,否则返回True
s + t 连接两个序列s和t
s*n 或 n*s 将序列s复制n次
s[i] 索引,返回s中的第i个元素, i是序列的序号
s[i: j] 或 s[i: j: k] 切片,返回序列s中第i到j以k为步长的元素子序列
s.index(x[,i[,j]]) 返回序列s中的第i到第j项元素中第一次出现元素x的位置
"""

列表的方法

"""
cmp(list1, list2):---------比较两个列表的元素 (python3已丢弃)
len(list):-----------------列表元素个数
max(list):-----------------返回列表元素最大值
min(list):-----------------返回列表元素最小值
list(seq):-----------------将元组转换为列表
list.append(obj):----------在列表末尾添加新的对象
list.count(obj):-----------统计某个元素在列表中出现的次数
list.extend(seq):----------在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj):-----------从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj):---将对象插入列表
list.pop(obj=list[-1]):----移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj):----------移除列表中某个值的第一个匹配项
list.reverse():------------反向列表中元素
list.sort([func]):---------对原列表进行排序
"""

遍历列表

lst = ['primary school', 'secondary school', 'high school', 'college']
for item in lst:
print(item, end=',')

x = 1.201
y = 1.3
print(x + y) # ?2.5010000000000003

lst = list(range(2, 21, 3))
i = 0
result = []
while i < len(lst):
result.append(lst[i] * lst[i])
i += 1
print(result, end='')

元组的基本操作

tup1 = (123, 'xya', 'zero', 'abc')
lst1 = list(tup1)
lst1.append(999)
tup1 = tuple(lst1)
print(tup1)

字典基本操作

'''
检索字典元素 key in dicts
dicts:字典名
key:键名
可以使用表达式dicts['key'],将返回key所对应的值
'''
dict1 = {
"name": "daibeis",
"age": 18,
"address": "jiangsu"
}
print("name" in dict1)
print("姓名:{} ".format(dict1['name']) + "年龄:{} ".format(dict1['age']) + "地址:{} ".format(dict1["address"]))
print(type(dict1["age"]))
"""
字典的常用方法
dicts:字典名 key:键名 value:值
dicts.keys()--------------------------返回所有键信息
dicts.values()------------------------返回所有值信息
dicts.items()-------------------------返回所有键值对
dicts.get(key, default)---------------键存在则返回相应的值,否则返回默认值
dicts.pop(key, default)---------------键存在则返回相应的值,同时删除键值对,否则返回默认值
dicts.popitem()-----------------------随即从字典中取出一个键值对,以元组(key,value)的形式返回
dicts.clear()-------------------------删除所有的键值对
del dicts[key]------------------------删除字典中的某个键值对
dicts.copy()--------------------------复制字典
dicts.update()------------------------更新字典,参数dict2为更新字典
"""
print(dict1.get("name"))
print(dict1.get("age1", "age1不在字典里"))
print(dict1.pop("name", "弹出name不成功"))
print(dict1.pop("email", "弹出email不成功"))

使用popitem()函数逐一删除键值对

print(dict1.popitem())
print(dict1.popitem())
print(dict1)

copy(): 通过copy()方法可以返回一个字典的复本,但新产生的字典与原字典id是不同的,用户修改一个字典对象时,不会对另一个字典对象产生影响

update(): 通过update()方法可以使用一个字典更新另一个字典,如果两个字典有相同的键存在,则键值对会进行覆盖

dict2 = {
"name": "daibeis",
"age": 18,
"address": "jiangsu"
}
dict3 = {
"name": "daibeis",
"birthday": "12/3",
"email": "heyares@163.com"
}
dict4 = dict2.copy()
print("{}".format(dict4 is dict2))
print(id(dict2))
print(id(dict4))
print("dict2:{}".format(dict2))
print("dict4:{}".format(dict4))
dict2.update(dict3)
print(dict2)
print(dict4)

"""
集合
1.集合的常用操作
创建集合:使用函数set()可以创建一个集合,没有快捷方式,必须使用set()函数
set()函数最多有一个参数,如果没有参数,则会创建一个空集合。如果有一个参数,
那么参数必须是可迭代的类型,例:字符串或列表,可迭代对象的元素将生成集合的成
员。

S、T为集合,x为集合中的元素  

S.add()----------------添加元素
S.clear()--------------清除S中的所有元素
S.copy()---------------复制集合
S.pop()----------------随机弹出S中的一个元素,S为空时产生KeyError异常
S.discard(x)-----------如果x在S中,移除该元素,x不存在不报异常
S.remove(x)------------如果x在S中,移除该元素,x不存在报KeyError异常
S.isdisjiont(T)--------判断集合中是否存在相同元素,如果S与T没有相同元素,返回True
len(S)-----------------返回S的元素个数

集合运算  

S&T或S.intersaction(T)------------------返回一个新集合(S和T得交集)
S|T或S.union(T)------------------------------------------------并集
S-T或S.difference(T)-------------------------------------------差集
S^T或S.symmetric_difference_update(T)--------------------------补集
S<=T或S.issubset(T)--------------------子集测试,如果S与T相同或是S和T中的子集, 返回True,否则返回False,可以用S=T或S.issuperset(T)------------------超集测试,如果S与T相同或是S和T中的超集,
返回True,否则返回False,可以用S>T判断S是否是T的真子集
"""
aset = set("python")
bset = set([1, 2, 3, 5, 2])
cset = set()
print("{}{}{}".format(aset, bset, cset))
bset.add(4)
bset.remove(5)
print(bset)
print(aset.isdisjoint(bset))
print(len(bset))
for x in aset: # 遍历集合
print("{}".format(x))
dset = set([9, 8, 7, 6, 5, 3])
set1 = dset & bset
set2 = bset | dset
set3 = dset - bset
set4 = dset ^ bset
print("b与d的交集是{}并集是{}差集是{}补集是{}".format(set1, set2, set3, set4))

"""
组合数据类型的应用
"""

--------------英文句子中的词频统计---------------------

sentence = "There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.\
  May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.\
  The happiest of people don’t necessarily have the best of everything;they just make the most of everything that comes along their way.Happiness lies for those who cry,those who hurt, those who have searched,and those who have tried,for only they can appreciate the importance of people\
  who have touched their lives.Love begins with a smile,grows with a kiss and ends with a tear.The brightest future will always be based on a forgotten past, you can’t go on well in lifeuntil you let go of your past failures and heartaches.\
  When you were born,you were crying and everyone around you was smiling.Live your life so that when you die,you're the one who is smiling and everyone around you is crying.\
  Please send this message to those people who mean something to you,to those who have touched your life in one way or another,to those who make you smile when you really need it,to those that make you see the brighter side of things when you are really down,to those who you want to let them know that you appreciate their friendship.And if you don’t, don’t worry,nothing bad will happen to you,you will just miss out on the opportunity to brighten someone’s day with this message.\
"

将文本中涉及的标点用空格替换

for ch in ",.?!';":
sentence = sentence.replace(ch, " ")

利用字典统计词频

words = sentence.split()
map1 = {}
for word in words:
if word in map1:
map1[word] += 1
else:
map1[word] = 1

对统计结果排序

items = list(map1.items())
items.sort(key=lambda x: x[1], reverse=True)

打印控制

for item in items:
word, count = item
print("{:<12}{:>5}".format(word, count))

------------------二分查找------------------------------

list1 = [1, 42, 3, -7, 8, 9, -10, 5]

二分查找要求查找的序列手机有序的,假设是升序列表

list1.sort()
print(list1)
find = 9 # 要查找的数据

low = 0
high = len(list1) - 1
flag = False
while low <= high: mid = int((low + high) / 2) if list1[mid] == find: flag = True break # 左半边 elif list1[mid] > find:
high = mid - 1
# 右半边
else:
low = mid + 1

if flag == True:
print("你查找的数据{},是第{}个元素".format(find, mid + 1))
else:
print("没有你要查找的数据")