一、 set集合
set,无序,不重复序列
创建列表
#创建set集合的几种方式
se = {123,456}
s = set()
s1 = list(se)
print(set([11,22,33,22]))
print(type(se))
找出s1中存在,s2中不存在的值
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.difference(s2)
{11}
s1于s2的对称差集
s1 = {11,22,33}
s2 = {11,22,44}
s3 = s1.symmetric_difference(s2)
print(s3)
输出
{33, 44}
移除指定元素
s1 = {11,22,33}
#移除指定元素,元素不存在时不报错
s1.discard(11)
print(s1)
输出
{33, 22}
取set中交集
s1 = {11,22,33}
s2 = {11,22,44}
print(s1.intersection(s2))
{11, 22}
批量添加元素
s1 = {11,22,33}
s3 = [6,23,4]
s1.update(s3)
print(s1)
输出
{33, 4, 6, 11, 22, 23}
set的详细方法
class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
"""
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
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. 清除内容"""
pass
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. 浅拷贝 """
pass
def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set. A中存在,B中不存在,差异比对
(i.e. all elements that are in this set but not the others.)
"""
pass
def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. 从当前集合中删除和B中相同的元素"""
pass
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
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
def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another. 取交集并更更新到A中 """
pass
def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. 如果没有交集,返回True,否则返回False"""
pass
def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. 是否是子序列"""
pass
def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. 是否是父序列"""
pass
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty. 移除元素
"""
pass
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
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
def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
pass
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
def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. 更新 """
pass
二、 python 函数
- 定义函数
- 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。
- 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
- 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
- 函数内容以冒号起始,并且缩进。
- return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
- 语法定义及调用函数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 定义函数
def printme( str ):
"打印任何传入的字符串"
print str;
return;
# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");
- 函数返回值
- 在函数中,一旦执行return,函数体就会停止向下执行
#!/usr/bin/python3
def f1():
print(1234)
return '12'
print(496)
f1()
输出:
1234
- 函数传参
#!/usr/bin/python3
#函数传入参数
def send(aa,bb):
print(aa,bb)
send('11','22')
#输出
11,22
#传入默认参数,默认参数必须在传参列表的末尾
def send(aa,bb='OK'):
print(aa,bb)
send('11')
#输出
11,OK
- 函数动态参数1
#* 可以传入N个参数,默认将参数写到元组里面
def f1(*args):
print(args)
li = [22,3,5,7]
#传参时带*和不带是不一样的
f1(li) #将整个列表都传入
f1(*li) #将列表转换为元组,相当于做了一个for循环
f1('11',22,33,44)
输出
([22, 3, 5, 7],)
(22, 3, 5, 7)
('11', 22, 33, 44)
- 函数动态参数2
#当参数前面是2*号是,传入参数是需要传入一个key,一个value,默认把参数放到字典中
def f1(**args):
print(args)
dic = {'k1':'v1','k2':'v2'}
# 传入时传入两个*,会将字典原原本本写进去,两个键值对
f1(**dic)
#这样会变成一个键值对
f1(v1=dic)
f1(key='vv',k=11)
输入
{'k1': 'v1', 'k2': 'v2'}
{'v1': {'k1': 'v1', 'k2': 'v2'}}
{'key': 'vv', 'k': 11}
-----------------------------------------------------------------------
#可传入任何参数
def f1(*args,**kwargs):
print(args)
print(kwargs)
dic = {'k1':'v1','k2':'v2'}
f1(11,22,33,**dic)
f1(11,22,33,k1='v1',k2='v2')
#注意不能这么写
#f1(11,22,33,k1='v1',k2='v2',**dic)
输出
(11, 22, 33)
{'k1': 'v1', 'k2': 'v2'}
(11, 22, 33)
{'k1': 'v1', 'k2': 'v2'}
三、 全局变量
- 规则是定义全局变量时需要将变量名大写
-
没写到函数里面的都是全局变量,在所有作用域里面都能读;
-
函数内修改全局变量时需要在函数内加上关键字global,实例如下:
- 特殊:当全局变量为字典列表时,可修改,但不可重新赋值
#!/usr/bin/python3
NAME = 6
#修改全局变量时加上global
def f1():
global NAME
print(NAME)
NAME = 2
print(NAME)
f1()
输入:
6
2
——————————————————————————————-
#如果不加global,就会报下面的错误
X = 6
def f1():
print(X)
x = 2
print(X)
f1()
输入:
UnboundLocalError: local variable 'X' referenced before assignment
四、三元运算(if-else简写)
# 这样写需要4行完成
if 1 == 1:
name = 'aa'
else:
name = 'bb'
# print(name)
# 这样只要一行就行了,如果1=1 则name='aa'否则name = 'bb'
name = 'aa' if 1 == 1 else 'bb'
print(name)
五、Lambda 表达式
- lambda 语法:lambda arg1, arg2, ....: expression
- lambda中arg1、arg2等于函数式的参数,之後你可以在expression中使用這些參數。注意!lambda是运算式,不是陳述句,你在:之後的也必須是運算式,lambda中也不能有區塊,這表示一些小的運算任務你可以使用lambda,而較複雜的邏輯你可以使用def來定義。
#这两种写法完全是一样的
def f1(a1,b1):
return a1+b1
f2 = lambda a1,b1: a1+b1
print(f1(2,3))
print(f2(5,1))
六、 内置函数
- abs() 取绝对值, abs(-1)
- all() 当传参里所有的布尔值为真,返回的结果才为真
- any() 当传参里任何一个的布尔值为真,返回的结果就为真
- ascii() 自动执行对象的__repr__方法
- bin() 接收一个十进制,将十进制转换成二进制
- oct() 接收一个十进制,将十进制转换成八进制
- hex() 接收一个十进制,将十进制转换成十六进制
- bytes() 将字符串转换为字节类型 ,bytes('字节','utf-8') #python3
- str() 将字节转换为字符串, str(b'\xe9\xa3\x9e',encoding="utf-8")
七、文件操作
- 打开文件(如果打开文件出现乱码,可能是encoding='' 出现问题,(一般在追加内容是打开方式都用r+)
#!/usr/bin/python3
f = open('db','r') #已只读方式打开文件
f = open('db','x') #文件存在就报错,文件不存,创建并写入内容
f = open('db','w') #只写,先清空
f = open('db','a') #追加内容
#如果文件打开是乱码,可能你保存的时候就是gbk格式的文件,需要进行转化一下
f = open('db','r', encoding='utf-8')
# 读写模式后面加上b就是以二进制的方式读取文件
f = open('db','rb')
f = open('db','r+') #可读可写,位置指针放在末尾
- 操作文件
#!/usr/bin/python3
# 二进制和普通读取方式区别,默认read()无参数,则读全部
f = open('user_list.txt','rb')
print(f.read(),type(f.read()))
f.close()
print('---'*10)
z = open('user_list.txt','r')
print(z.read(),type(z.read()))
z.close()
#输出
b'admin|123\nadmin2|123\nadmin3|fsg' <class 'bytes'>
------------------------------
admin|123
admin2|123
admin3|fsg <class 'str'>
# 当文件以二进制方式打开的时候,写入
f = open('user_list.txt','ab')
f.write(bytes('hello', encoding='utf8'))
f.close()
-------------------------------
#调整读取位置指针,如果有值会覆盖掉,读取位置是以字节的方式读取的,如果是那个位置是中文,很可能就会出现乱码
z = open('user_list.txt','r')
z.seek(12) #跳转到指定位置
z.tell() #获取当前文件指针的位置
z.write() #写数据,打开方式有b按字节
z.fileno()
z.flush() #强制刷新到硬盘上
z.readable() #判断内容是否可读
z.readline() #仅读取一行
z.truncate() #截断,指针后面内容全部删除
#for循环文件对象,一行一行的读取文件
f = open('db','r')
for line in f:
print(f)
f.close()
- 关闭文件
# z = open('user_list.txt','r')
# print(z.read(),type(z.read()))
# z.close() #关闭文件
- 文件操作 with open()
# 通过with 处理上下文,同时打开两个文件,在python3中支持
# 将aa文件中前10行,写入到bb文件中
with open('aa','r') as f, open('bb','w') as f2:
lines = 0
for line in f: #读一行,写一行
lines += 10
if lines <= 10:
f2.write(line)
else:
break
# 将aa文件中的file改成files,写到bb文件中
with open('aa','r') as f, open('bb','w') as f2:
for line in f: #读一行,写一行
now_str = line.replace('file','files')
f2.write(now_str)
916

被折叠的 条评论
为什么被折叠?



