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表示,例如: ...
随机推荐
- Forms组件与钩子函数
目录 一:Forms组件 1.案例需求: 2.前端 3.后端 二:form表单前后端动态交互 1.form组件 2.为什么数据效验非要去后端 不能在前端利用js直接完成呢? 3.举例:购物网站 三:基 ...
- python的数据结构和基本语法
1.支持的数据类型 str(字符串类型).int(整型).flout(浮点型).bool(逻辑值).complex(复数[数学上的]).bytes(字节型).list(列表).tuple(元组[不可以 ...
- 理解并手写 call() 函数
手写自己的call,我们要先通过call的使用,了解都需要完成些什么功能? call()进行了调用,是个方法,已知是建立在原型上的,使用了多个参数(绑定的对象+传递的参数). 我们把手写的函数起名为m ...
- 你真的懂TSP吗
整数规划-模型 2022年2月26日 TSP问题 有一个邮递员,他每天负责向100个客户的家门口送一份报纸,他希望走最短的总路程来完成配送任务,这是TSP问题最原始的场景.用理论描述就是:找一个路径 ...
- 安装Win7与Ubuntu16.04双系统操作教程
安装主要分为以下几步: 一. 下载Ubuntu 16.04镜像软件: 二. 制作U盘启动盘使用ultraISO: 三. 安装Ubuntu系统: 四. 用EasyBCD 创建启动系统启动引导: (根据个 ...
- 编程篇——Java学习路线
1.java基础编程2.Java多线程编程(并发)3.Java设计模式(重构)4.Java调试技术(Java虚拟机)5.Java常用框架学习篇6.Java开发之web篇
- CentOS7.5环境下安装配置GitLab
1. 安装依赖软件 yum -y install policycoreutils openssh-server openssh-clients postfix 2.设置postfix开机自启,并启动, ...
- ChIP-seq技术介绍|易基因
大家好,这里是专注表观组学十余年,多组学科研服务领跑者的易基因. 染色质免疫沉淀后测序(ChIP seq)是一种针对DNA结合蛋白.组蛋白修饰或核小体的全基因组分析技术.由于二代测序技术的巨大进步,C ...
- linux上使用nginx、uwsgi部署django项目
参考:CentOS7下部署Django项目详细操作步骤 注意事项: 在虚拟环境中操作,虚拟环境中安装nginx.uwsgi,虚拟环境外需安装uwsgi -- 临时关闭防火墙:systemctl sto ...
- MariaDB 存储引擎一览(官方文档翻译)
inline-translate.translate { } inline-translate.translate::before, inline-translate.translate::after ...