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表示,例如: ...
随机推荐
- c++ 11 线程池---完全使用c++ 11新特性
前言: 目前网上的c++线程池资源多是使用老版本或者使用系统接口实现,使用c++ 11新特性的不多,最近研究了一下,实现一个简单版本,可实现任意任意参数函数的调用以及获得返回值. 0 前置知识 首先介 ...
- JVM探究 面试题 JVM的位置 三种JVM:HotSpot 新生区 Young/ New 养老区 Old 永久区 Perm 堆内存调优GC的算法有哪些?标记清除法,标记压缩,复制算法,引用计数法
JVM探究 面试题: 请你弹弹你对JVM的理解?Java8虚拟机和之前的变化更新? 什么是OOM?什么是栈溢出StackOverFlowError?怎么分析 JVM的常用调优参数有哪些? 内存快照如何 ...
- Play商店显示需要进行身份认证。您需要登录自己的Google帐户
前段时间把一加6系统从H2OS换到OxygenOS,Play商店死活不能登录,网络配置等问题已经排除,重装Google全家桶也没有解决问题,最后找到原因. 解决办法:在应用列表中找到Google Pl ...
- 恢复mysql管理员密码
1.向mysqld server 发送kill命令关掉mysqld server(不是 kill -9),存放进程ID的文件通常在MYSQL的数据库所在的目录/var/lib/mysql中.# kil ...
- spring——整合Mybatis
一.Mybatis整合spring 步骤: 导入相关jar包 junit mybatis mysql数据库 spring-webmvc aop织入 mybatis-spring spring-jdbc ...
- 数据库原理 之MySQL
数据库种类: 关系型数据库: mysql 专注于数据安全 和功能 ,存取时 会有表的结构化操作解析sql语句---- 丢给磁盘存取 ----取出,结构化成表 常用关系型数据库产品介绍oracle数据库 ...
- hanoi(老汉诺塔问题新思维)
#include <stdio.h> //第一个塔为初始塔,中间的塔为借用塔,最后一个塔为目标塔 int i=1;//记录步数 void move(int n, char from,cha ...
- 100行代码实现HarmonyOS“画图”应用,eTS开发走起!
本期我们给大家带来的是"画图"应用开发者Rick的分享,希望能给你的HarmonyOS开发之旅带来启发~ 介绍 2021年的华为开发者大会(HDC2021)上,HarmonyOS ...
- 序列化和反序列化&持久化
java序列化与反序列化全讲解 之前一知半解的,对于序列化的概念,为啥用,哪里用也不清楚,现在深入了解协议,先把序列化这个这个概念和和使用场景搞清楚
- Oracle 关于v$之类的视图使用说明
官方文档:https://docs.oracle.com/en/database/oracle/oracle-database/19/cncpt/data-dictionary-and-dynamic ...