Python的组合数据类型
"""
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是否是T的真子集
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("没有你要查找的数据")
Python的组合数据类型的更多相关文章
- python的组合数据类型及其内置方法说明
python中,数据结构是通过某种方式(例如对元素进行编号),组织在一起数据结构的集合. python常用的组合数据类型有:序列类型,集合类型和映射类型 在序列类型中,又可以分为列表和元组,字符串也属 ...
- 【Python】组合数据类型
集合类型 集合类型定义 集合是多个元素的无序组合 集合类型与数学中的集合概念一致 集合元素之间无序,每个元素唯一,不存在相同元素 集合元素不可更改,不能是可变数据类型 理解:因为集合类型不重复,所以不 ...
- Python Revisited Day 03 (组合数据类型)
目录 第三章 组合数据类型 3.1 序列类型 3.1.1 元组 3.1.2 命名的元组 (collections.nametuple()) 3.1.3 列表 (查询有关函数点这) 3.1.4 列表内涵 ...
- Python字符串、组合数据类型练习
一.Python字符串练习 1.http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html 取得校园新闻的编号. (这个方法就很多了,一般方 ...
- Python学习笔记(六)Python组合数据类型
在之前我们学会了数字类型,包括整数类型.浮点类型和复数类型,这些类型仅能表示一个数据,这种表示单一数据的类型称为基本数据类型.然而,实际计算中却存在大量同时处理多个数据的情况,这种需要将多个数据有效组 ...
- python组合数据类型和数据结构
//2019.12-071.pyhton里面组合数据类型主要有三种:集合(set).序列(字符串str.列表list and 元组tuple)和映射(字典dic)2.集合类型一般使用大括号{}来进行表 ...
- Python基础篇(四)_组合数据类型的基本概念
Python基础篇——组合数据类型的基本概念 集合类型:元素的集合,元素之间无序 序列类型:是一个元素向量,元素之间存在先后关系,通过序号进行访问,没有排他性,具体包括字符串类型.元组类型.列表类型 ...
- python 基础之数据类型
一.python中的数据类型之列表 1.列表 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 二.列表常用操作 >切片>追加>插入>修改& ...
- Python学习之数据类型
整数 Python可以处理任意大小的整数,在程序中的表示方法和数学上的写法一模一样,例如:1,100,-8080,0,等等. 用十六进制表示整数比较方便,十六进制用0x前缀和0-9,a-f表示,例如: ...
随机推荐
- find: `./folder': No such file or directory 错误处理
这是我正在处理的目录的内容: misha@hp-laptop:~/work/c/5$ ls -l total 8 -rw-rw-r-- 1 misha misha 219 May 20 15:37 d ...
- CentOS下mysql常用命令
CentOS下mysql常用命令 1.开启和关闭 1.1.开启 service mysql start 1.2.关闭 service mysql stop 1.3.重启 service mysql ...
- w10环境vs2017,vs2019配置Opengl快捷方法
最近,计算机图形学老师向我们布置了任务,配置自己的opengl.百度之后我发现很多教程和方法尝试之后,我发现一种简单的方法来分享给大家. 首先我的软件配置是w10专业版系统+Visual Stdio ...
- CF802O题解
太厉害啦,出题人究竟是怎么想到的. 首先这题很显然可以使用费用流:对于 \(i \leq j\),连接一条边 \((i,j+n)\),流量为 \(1\),费用为 \(a_i+b_j\).最后连接 \( ...
- npm vue路由配置
npm vue路由 复习:1.README.md文件:保存如何使用的命令 (1) npm install:拷项目时可以不拷node_modules文件,运行该命令时,会自动下载node_mod ...
- C++ struct结构体内存对齐
•小试牛刀 我们自定义两个结构体 A 和 B: struct A { char c1; char c2; int i; double d; }; struct B { char c1; int i; ...
- idea创建web项目以及配置Tomcat
废话不多说,直接上干活: 1.在project中现创建好module,也就是java web项目 2.把路径名写清楚就行了 3.创建在WEB-INF上右击创建classes和lib以存储class编译 ...
- django之model,crm操作
一.字段 AutoField(Field) - int自增列,必须填入参数 primary_key=True BigAutoField(AutoField) - bigint自增列,必须填入参数 pr ...
- 5月28日 python学习总结 CSS学习(二)
CSS属性相关 宽和高 width属性可以为元素设置宽度. height属性可以为元素设置高度. 块级标签才能设置宽度,内联标签的宽度由内容来决定. 字体属性 文字字体 font-family可以把多 ...
- 从零开始,开发一个 Web Office 套件(14):复制、粘贴、剪切、全选
这是一个系列博客,最终目的是要做一个基于 HTML Canvas 的.类似于微软 Office 的 Web Office 套件(包括:文档.表格.幻灯片--等等). 博客园:<从零开始, 开发一 ...