python 笔记2

1、 set集合

set,无序,不重复序列

建立列表php

#建立set集合的几种方式
se = {123,456}
s = set()
s1 = list(se)
print(set([11,22,33,22]))
print(type(se))

找出s1中存在,s2中不存在的值python

>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.difference(s2)
{11}

 s1于s2的对称差集express

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中交集ui

s1 = {11,22,33}
s2 = {11,22,44}
print(s1.intersection(s2))

{11, 22}

批量添加元素this

s1 = {11,22,33}

s3 = [6,23,4]
s1.update(s3)
print(s1)


输出
{33, 4, 6, 11, 22, 23}

set的详细方法spa

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

2、 python 函数

  • 定义函数
  1. 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()
  2. 任何传入参数和自变量必须放在圆括号中间。圆括号之间能够用于定义参数。
  3. 函数的第一行语句能够选择性地使用文档字符串—用于存放函数说明。
  4. 函数内容以冒号起始,而且缩进。
  5. 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'}

3、 全局变量

  • 规则是定义全局变量时须要将变量名大写
  • 没写到函数里面的都是全局变量,在全部做用域里面都能读;指针

  • 函数内修改全局变量时须要在函数内加上关键字global,实例以下:code

  • 特殊:当全局变量为字典列表时,可修改,但不可从新赋值
#!/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

4、三元运算(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)

5、Lambda 表达式

  • lambda 语法:lambda arg1, arg2, ....: expression
  • lambda中arg一、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))

6、 内置函数

  • abs() 取绝对值, abs(-1)
  • all()   当传参里全部的布尔值为真,返回的结果才为真
  • any()   当传参里任何一个的布尔值为真,返回的结果就为真
  • ascii()    自动执行对象的__repr__方法
  • bin()     接收一个十进制,将十进制转换成二进制
  • oct()     接收一个十进制,将十进制转换成八进制
  • hex()    接收一个十进制,将十进制转换成十六进制
  • bytes()   将字符串转换为字节类型 ,bytes('字节','utf-8')    #python3
  • str()      将字节转换为字符串, str(b'\xe9\xa3\x9e',encoding="utf-8")

7、文件操做

  • 打开文件(若是打开文件出现乱码,多是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)
相关文章
相关标签/搜索