三元运算

三元运算(三目运算),是对简单的条件语句的缩写。

# 书写格式

result = 值1 if 条件 else 值2

# 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量

if 1==1:    name = "wangxin"else:    name = "yuehan"#如果1=1成立,name为wangxin,否则...name = "wangxin" if 1==1 else "yuehan"

set

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

深浅拷贝

一、数字和字符串

对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

import copy# ######### 数字、字符串 #########n1 = 123# n1 = "i am wangxin age 10"print(id(n1))# ## 赋值 ##n2 = n1print(id(n2))# ## 浅拷贝 ##n2 = copy.copy(n1)print(id(n2))  # ## 深拷贝 ##n3 = copy.deepcopy(n1)print(id(n3))

二、其他基本数据类型

对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

1、赋值

赋值,只是创建一个变量,该变量指向原来内存地址,如:

n1 = {"k1": "wu", "k2": 123, "k3": ["wangxin", 456]}  n2 = n1

  

2、浅拷贝

浅拷贝,在内存中只额外创建第一层数据

import copy  n1 = {"k1": "wu", "k2": 123, "k3": ["wangxin", 456]}  n3 = copy.copy(n1)

3、深拷贝

深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

import copy  n1 = {"k1": "wu", "k2": 123, "k3": ["wangxin", 456]}  n4 = copy.deepcopy(n1)


函数

  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可

  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”

函数式编程最重要的是增强代码的重用性和可读性

定义和使用

def 函数名(参数):           ...    函数体    ...    返回值

函数的定义主要有如下要点:

  • def:表示函数的关键字

  • 函数名:函数的名称,日后根据函数名调用函数

  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...

  • 参数:为函数体提供数据

  • 返回值:当函数执行完毕后,可以给调用者返回数据。

1、返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

以上要点中,比较重要有参数和返回值:

def 发送短信():           发送短信的代码...       if 发送成功:        return True    else:        return False      while True:           # 每次执行发送短信函数,都会将返回值自动赋值给result    # 之后,可以根据result来写日志,或重发等操作       result = 发送短信()    if result == False:        记录日志,短信发送失败...

2、参数

函数的有三中不同的参数:

普通参数

默认参数

动态参数

# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参def func(name):    print name# ######### 执行函数 ######### #  'wupeiqi' 叫做函数func的实际参数,简称:实参func('wupeiqi')普通参数
def func(name, age = 18):        print "%s:%s" %(name,age)# 指定参数func('wupeiqi', 19)# 使用默认参数func('wangxin')注:默认参数需要放在参数列表最后默认参数
def func(*args):    print args# 执行方式一func(11,33,4,4454,5)# 执行方式二li = [11,2,2,3,3,4,54]func(*li)动态参数
def func(**kwargs):    print args# 执行方式一func(name='wupeiqi',age=18)# 执行方式二li = {'name':'wupeiqi', age:18, 'gender':'male'}func(**li)动态参数

# def f2():#     print(123)# r = f2()# print(r) #python的函数会自动return一个空值None# def sendmail(xxoo)#形式参数## ret =sendmail("wangxin") #实际参数## def send(xxoo,content,xx="OK")#默认参数,不给xx传参就是默认值"OK",默认参数必须放到参数列表后面,有多个就依次放# def send(xxoo,content)# send("wangxin","sb") #按顺序传参# send(content="wangxin",xxoo="sb")#指定参数,传参的时候指定'''#1、普通参数(严格按照顺序,将实际参数赋值给形式参数)#2、默认参数(必须放在参数列表的最后)#3、指定参数#4、动态参数:# *  默认将传入的参数,全部放置在元组中def fa(*args):    print(args,type(args))fa(11,22,'wangxin')li = [11,22,"wangxin","yaoyao"]fa(li,99) #将列表当作一个元素传到元组里面fa(*li)#将列表里的每一个元素都转化成元组的每一个元素 ** 默认将传入的参数,全部放置在字典中def fa(**args):    print(args,type(args))fa(n1="wangxian",n2=20)dic = {'k1':'v1','k2':'v2'}fa(**dic)#将字典里的每一个元素都转化成字典的每一个元素#5、万能参数  *args,**kwargs顺序固定def fb(*args,**kwargs):    print(args)    print(kwargs)fb(11,22,33,44,k1='v1',k2='2')'''

内置函数

#abs()取绝对值

"""

# all() 所有为真,才为真
# any() 任何一个为真,就为真
#0,None,"",[],()
#print(bool())
n = all([1,2,3,4,0])
print(n)
"""
# bin() 0b 二进制
# oct() 0c 十进制
# hex() 0x 十六
# print(bin(5))
# print(oct(9))
# print(hex(15))
#utf-8 一个汉字:三个字节
#gbk 一个汉字:二个字节
#字符串转换字节类型
#bytes(要转换的字符串,按照什么编码)
s = "测试"
n = bytes(s,encoding="utf-8")
print(n)
n = bytes(s,encoding="gbk")
print(n)
#字节转化成字符串
new_str = str( bytes(s,encoding="utf-8"),encoding="utf-8")
print(new_str)

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

打开文件

操作文件

关闭文件

一、打开文件

文件句柄 = open('文件路径', '模式')

   

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

r ,只读模式【默认】

w,只写模式【不可读;不存在则创建;存在则清空内容;】

x, 只写模式【不可读;不存在则创建,存在则报错】

a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

r+, 读写【可读,可写】

w+,写读【可读,可写】

x+ ,写读【可读,可写】

a+, 写读【可读,可写】

 "b"表示以字节的方式操作

rb  或 r+b

wb 或 w+b

xb 或 w+b

ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

#打开文件# f = open('db','r',encoding="utf-8")#当打开一个文件出现乱码,就要考虑编码的问题# f = open('db','w')#只写,先清空文件# f = open('db','a')#追加# f = open('db','x')#如果文件存在就报错,不存在就创建文件并写内容"""f = open('db','rb')#直接找二进制字节,告诉python不需要处理,读写都是二进制字节f = open('db','rb')data = f.read()print(data,type(data))"""# f = open('db','a')# f.write("wangxin")# f.close()# f = open('db','ab')# f.write(bytes("wangxin", encoding="utf-8"))# f.close()# +号各种读写的区别# f = open('db','r+',encoding="utf-8")# #如果打开模式无b,则read按照字符读取# data = f.read(1)# print(data)# print(f.tell())#获取当前指针的位置,tell当前指针所在的位置(字节)# f.seek(1)#将指针的位置定位在哪里# f.write("777") #当前指针位置开始向后覆盖,写入数据要覆盖原数据# f.close()## #a+永远都是在最后写,调指针无效# #w+会先清空,再写的内容可以读

二、操作

    def close(self, *args, **kwargs): # real signature unknown        关闭文件        pass    def fileno(self, *args, **kwargs): # real signature unknown        文件描述符          pass    def flush(self, *args, **kwargs): # real signature unknown        刷新文件内部缓冲区        pass    def isatty(self, *args, **kwargs): # real signature unknown        判断文件是否是同意tty设备        pass    def read(self, *args, **kwargs): # real signature unknown        读取指定字节数据        pass    def readable(self, *args, **kwargs): # real signature unknown        是否可读        pass    def readline(self, *args, **kwargs): # real signature unknown        仅读取一行数据        pass    def seek(self, *args, **kwargs): # real signature unknown        指定文件中指针位置        pass    def seekable(self, *args, **kwargs): # real signature unknown        指针是否可操作        pass    def tell(self, *args, **kwargs): # real signature unknown        获取指针位置        pass    def truncate(self, *args, **kwargs): # real signature unknown        截断数据,仅保留指定之前数据        pass    def writable(self, *args, **kwargs): # real signature unknown        是否可写        pass    def write(self, *args, **kwargs): # real signature unknown        写内容        pass
# 操作文件# 通过源码查看功能# read()#无参数:读全部#        有参数:有b,按字节;无b,按字符# tell() 获取当前指针位置(字节)# seek()指针跳转到指定位置(字节)# write() 写数据 b,字节;无b,字符# close()# fileno()#flush() 强制把数据刷到硬盘上#readline() 仅读取一行#truncate 截断,将指针后面的内容清空#for循环文件对象,一行一行的读取文件# for line in f:#     print(line)

三、关闭文件

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
        
    ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2:
    pass

# f.close()# with open("xb") as f:#     pass

lambda表达式

对于简单的函数,存在一种简便的表示方式,即:lambda表达式

# ###################### 普通函数 ####################### 定义函数(普通方式)def func(arg):    return arg + 1    # 执行函数result = func(123)    # ###################### lambda ######################    # 定义函数(lambda表达式)my_lambda = lambda arg : arg + 1    # 执行函数result = my_lambda(123)------------------------------------------------------def f1(a1):    return a1 + 100f2 = lambda a1: a1 + 100f3 = lambda a1,a2: a1 + a2 + 100ret = f1(10)print(ret)print(f2(10))

全局变量

#全局变量,所有的作用域都可读

#对全局变量进行重新赋值,需要global
#特殊:列表、字典,可修改,不可重新赋值
#全局变量都大写,默认的规则

NAME = "wangxin"def f1():    age = 18#    global NAME # 表示,name是全局变量,可以修改函数外面的全局变量#    NAME = "yuehan"    print(age,NAME)def f2():    age = 20    print(age,NAME)f1()f2()