(四)、python 集合与格式化
一、set 集合
集合:可以包含多个元素,用逗号分割“,” 集合的作用:去重,关系运算,
1.不同元素组成
2.无序
3.集合中元素必须是不可变类型(可hash,可作为字典的key)
使用方法:
1)集合打印
# s = set('hello')
# print(s)
# 返回:{'h', 'e', 'o', 'l'} #无序的特性
# s=set(['alex','alex','sb'])
# print(s)
# 返回:{'sb', 'alex'} #无序,不可重复
2)add:添加
# s={1,2,3,4,5,6}
# s.add('s')
# s.add('3')
# s.add(3)
# print(s)
# 返回:{1, 2, 3, 4, 5, 6, '3', 's'}
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set. This has no effect if the element is already present.
"""
pass
add(self, *args, **kwargs)
3)clear:清空集合
# s={1,2,3,4,5,6}
# s.clear()
# print(s)
# 返回:set()
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass
clear(self, *args, **kwargs)
4)copy:拷贝
# s={1,2,3,4,5,6}
# s1=s.copy()
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass
copy(self, *args, **kwargs)
5)删除
# s={'sb',1,2,3,4,5,6}
# print(s)
# 随机删
# s.pop() #返回:{2, 3, 4, 5, 6, 'sb'}
# 指定删除
# s.remove('sb') #返回:{1, 2, 3, 4, 5, 6}
# s.remove('hellolllll') #删除元素不存在会报错
# s.discard('hellosb') #删除元素不存在不会报错
# print(s)
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass
pop(self, *args, **kwargs)
def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
"""
pass
remove(self, *args, **kwargs)
def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member. If the element is not a member, do nothing.
"""
pass
discard(self, *args, **kwargs)
关系运算:
# python_l=['lcg','szw','zjw']
# linux_l=['lcg','szw'] # 关系运算 打印即在 python_l 又在 linux_l里的内容
# python_and_linux=[]
# for p_name in python_l:
# if p_name in linux_l:
# python_and_linux.append(p_name)
# print(python_and_linux)
利用集合进行去重
# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# print(p_s,'\n',l_s)
# 返回:
{'szw', 'lcg', 'zjw'}
{'sb', 'szw', 'lcg'}
6)intersection:求交集
# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# print(p_s,l_s) #返回:{'szw', 'zjw', 'lcg'} {'szw', 'sb', 'lcg'}
# print(p_s.intersection(l_s)) #返回:{'szw', 'lcg'}
# print(p_s&l_s) #返回:{'szw', 'lcg'}
def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.)
"""
pass
intersection(self, *args, **kwargs)
7)union:求并集
# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# print(p_s.union(l_s))
# print(p_s|l_s)
def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set. (i.e. all elements that are in either set.)
"""
pass
union(self, *args, **kwargs)
8) difference:求差集
# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# 存在于p_s 不存在于 l_s
# print('差集:',p_s-l_s) #返回:差集: {'zjw'}
# print(p_s.difference(l_s)) #返回:{'zjw'}
# 存在于l_s,不存在于 p_s
# print('差集:',l_s-p_s) #返回:差集: {'sb'}
# print(l_s.difference(p_s)) #返回:{'sb'}
def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.)
"""
pass
difference(self, *args, **kwargs)
9)symmetric_difference: 交叉补集 合到一起 扣去共同的部分
# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# print('交叉补集:',p_s.symmetric_difference(l_s)) #返回:交叉补集: {'sb', 'zjw'}
# print('交叉补集:',p_s^l_s) #返回:交叉补集: {'sb', 'zjw'}
def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.)
"""
pass
symmetric_difference(self, *args, **kwargs)
10)difference_update:差集 并将差集赋给集合
# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# print(p_s,l_s)
# # print('差集:',p_s-l_s)
# #下面两个作用相同
# # p_s=p_s-l_s
# p_s.difference_update(l_s)
# print(p_s)
def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. """
pass
difference_update(self, *args, **kwargs)
11)isdisjoint :判断是否是相交集
# 两个集合如果没有相同部分就返回 True 有相同的就返回 False
# s1={1,2}
# s2={3,5}
# print(s1.isdisjoint(s2)) #返回:True
def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. """
pass
isdisjoint(self, *args, **kwargs)
12) issubset:子集
# s1.issubset() s1<=s2 s1是s2的子集
# s1={1,2}
# s2={1,2,3}
# print(s1.issubset(s2)) #s1 是s2 的子集返回 True
# print(s2.issubset(s1)) #不是子集返回 False
def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. """
pass
issubset(self, *args, **kwargs)
13)issuperset:父级
# s1={1,2}
# s2={1,2,3}
# print(s2.issuperset(s1)) #s2 是s1 的父级 True
def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. """
pass
issuperset(self, *args, **kwargs)
14)update:更新
# s1={1,2}
# s2={1,2,3}
# # s1.update(s2) #更新多个值
# # s1.add(1,2,3,4) #会报错 ,add只能更新一个值
# # s1.union(s2) #不更新
# s1.update((3,4,)) #可迭代的值都可以传
# print(s1)
def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. """
pass
update(self, *args, **kwargs)
15)frozenset:定义不可变集合
# s=frozenset('hello')
# print(s)
二、字符串格式化
Python的字符串格式化有两种方式: 百分号方式、format方式
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存
1、百分号方式
%[(name)][flags][width].[precision]typecode
- (name) 可选,用于选择指定的key
- flags 可选,可供选择的值有:
- + 右对齐;正数前加正好,负数前加负号;
- - 左对齐;正数前无符号,负数前加负号;
- 空格 右对齐;正数前加空格,负数前加负号;
- 0 右对齐;正数前无符号,负数前加负号;用0填充空白处
- width 可选,占有宽度
- .precision 可选,小数点后保留的位数
- typecode 必选
- s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
- r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
- c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
- o,将整数转换成 八 进制表示,并将其格式化到指定位置
- x,将整数转换成十六进制表示,并将其格式化到指定位置
- d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
- e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
- E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
- f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
- F,同上
- g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
- G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
- %,当字符串中存在格式化标志时,需要用 %%表示一个百分号
注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式
常用格式化:
|
1
2
3
4
5
6
7
8
9
10
11
|
tpl = "i am %s" % "alex"tpl = "i am %s age %d" % ("alex", 18)tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}tpl = "percent %.2f" % 99.97623tpl = "i am %(pp).2f" % {"pp": 123.425556, }tpl = "i am %.2f %%" % {"pp": 123.425556, } |
2、Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
- fill 【可选】空白处填充的字符
- align 【可选】对齐方式(需配合width使用)
- <,内容左对齐
- >,内容右对齐(默认)
- =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
- ^,内容居中
- sign 【可选】有无符号数字
- +,正号加正,负号加负;
- -,正号不变,负号加负;
- 空格 ,正号空格,负号加负;
- # 【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
- , 【可选】为数字添加分隔符,如:1,000,000
- width 【可选】格式化位所占宽度
- .precision 【可选】小数位保留精度
- type 【可选】格式化类型
- 传入” 字符串类型 “的参数
- s,格式化字符串类型数据
- 空白,未指定类型,则默认是None,同s
- 传入“ 整数类型 ”的参数
- b,将10进制整数自动转换成2进制表示然后格式化
- c,将10进制整数自动转换为其对应的unicode字符
- d,十进制整数
- o,将10进制整数自动转换成8进制表示然后格式化;
- x,将10进制整数自动转换成16进制表示然后格式化(小写x)
- X,将10进制整数自动转换成16进制表示然后格式化(大写X)
- 传入“ 浮点型或小数类型 ”的参数
- e, 转换为科学计数法(小写e)表示,然后格式化;
- E, 转换为科学计数法(大写E)表示,然后格式化;
- f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
- F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
- g, 自动在e和f中切换
- G, 自动在E和F中切换
- %,显示百分比(默认显示小数点后6位)
- 传入” 字符串类型 “的参数
常用格式化:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex') tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex']) tpl = "i am {0}, age {1}, really {0}".format("seven", 18) tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18]) tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) tpl = "i am {:s}, age {:d}".format(*["seven", 18]) tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18) tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15) |
注意:
# 传列表要加一个星号
# 传字典要加两个星号
(四)、python 集合与格式化的更多相关文章
- Python之路(第五篇) Python基本数据类型集合、格式化、函数
一.变量总结 1.1 变量定义 记录某种状态或者数值,并用某个名称代表这个数值或状态. 1.2 变量在内存中的表现形式 Python 中一切皆为对象,数字是对象,列表是对象,函数也是对象,任何东西都是 ...
- Python基本数据类型集合、格式化、函数
一.变量总结 1.1 变量定义 记录某种状态或者数值,并用某个名称代表这个数值或状态. 1.2 变量在内存中的表现形式 Python 中一切皆为对象,数字是对象,列表是对象,函数也是对象,任何东西都是 ...
- [19/09/19-星期四] Python中的字典和集合
一.字典 # 字典 # 使用 {} 来创建字典 d = {} # 创建了一个空字典 # 创建一个保护有数据的字典 # 语法: # {key:value,key:value,key:value} # 字 ...
- python(七)字符串格式化、生成器与迭代器
字符串格式化 Python的字符串格式化有两种方式:百分号方式.format方式 1.百分号的方式 %[(name)][flags][width].[precision]typecode (name) ...
- Python集合&字典
Python集合&字典 @ 目录 字典 字典的几种定义方式 第一种 第二种 第三种 字典的一些基本操作 通过key得到value 增加字典键值对 删除字典键值对 格式化操作 清空字典 复制字典 ...
- Django数据库性能优化之 - 使用Python集合操作
前言 最近有个新需求: 人员基础信息(记作人员A),10w 某种类型的人员信息(记作人员B),1000 要求在后台上(Django Admin)分别展示:已录入A的人员B列表.未录入的人员B列表 团队 ...
- Python基础-字符串格式化_百分号方式_format方式
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...
- Python 集合set添加删除、交集、并集、集合操作符号
在Python中集合set是基本数据类型的一种,它有可变集合(set)和不可变集合(frozenset)两种.创建集合set.集合set添加.集合删除.交集.并集.差集的操作都是非常实用的方法. 1. ...
- Python 的字符串格式化和颜色控制
(部分内容源自武神博客和网络收集.) Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两 ...
随机推荐
- Csharp:user WebControl Read Adobe PDF Files In Your Web Browser
namespace GeovinDu.PdfViewer { [DefaultProperty("FilePath")] [ToolboxData("<{0}:Sh ...
- Eclipse equinox implementation of OSGi
Bundle package org.osgi.framework; public interface Bundle extends Comparable<Bundle> { int UN ...
- 基于ArcGIS Runtime 100.x 的移动应用程序开发框架 开源
ArcGIS Runtime作为新一代的轻量GIS应用开发产品,它提供多种API,可以使用Android,iOS,Java,Mac OS X(Objective-C/Swift)..NET,Qt(C+ ...
- Android应用开发基础之三:数据存储和界面展现(三)
生成XML文件备份短信 创建几个虚拟的短信对象,存在list中 备份数据通常都是备份至sd卡 使用StringBuffer拼接字符串 把整个xml文件所有节点append到sb对象里 sb.appen ...
- Flask环境github及项目部署(十三)
(1) github项目搭建 1 连接GitHub hostnamectl set-hostname flask-dev # 设置 hostname,一般是主机名可以不更改 ssh-keygen # ...
- 使用WindowsService为宿主实装WCF 服务
1. 写WCF服务 创建一个接口类,与一个实现类.接口类上打上[ServiceContract]标签,需要暴露的服务方法上打上[OperationContract] (注意:增加System.Se ...
- 【Leetcode】【Easy】Plus One
Given a non-negative number represented as an array of digits, plus one to the number. The digits ar ...
- Struts的学习-eclipse与idea与struts的连接
1.建立一个空白工程(里面是没有文件的). 可以在文件放置找到项目文件夹 2.点击托管项目到码云 (ps:没有码云帐号的自己注册) 3.按快捷键:ctrl+alt+shift+s 呼出项目结构管理器, ...
- 深入理解linux源码安装三板斧
概述: 根据源码包中 Makefile.in 文件的指示,configure 脚本检查当前的系统环境和配置选项,在当前目录中生成 Makefile 文件(还有其它本文无需关心的文件),然后 make ...
- 一、Python安装下载
下载地址:https://www.python.org/downloads/ 因为Python3.X和2.X有部分不兼容,有些不向下兼容,现在3.5的资料和插件少,故我就学习的2.7.11了; 下载后 ...