python基础知识-set、函数、内置函数、文件操作

 

一、set

      set集合,是一个无序且不重复的元素集合

      1.创建

       

se = {"123","456"}
print (type(se))

s = set() #创建空集合
li = [11.22,11,22]
s1 =set(li)
print (s1)

#以下为执行结果
<class 'set'>
{11, 11.22, 22}

 

      2.功能

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
View Code

          1)添加 add()

s=set()
s.add(123)
s.add(123)
print (s)
#以下为执行结果
{123}

          2)不同difference()    symmetric_difference()

s1 ={11,22,33}
s2 ={22,33,44}
s3 = s1.difference(s2)# A存在 ,B不不存在
print (s1)
print (s2)
print (s3)
#以下执行结果:
{33, 11, 22}
{33, 44, 22}
{11}

s3 = s2.difference(s1)# B存在 ,A不不存在
print (s3)
#以下执行结果:
{44}

s3 = s1.symmetric_difference(s2) #AB互相不同的集合
print (s3)
#以下执行结果:
{11, 44}

 

          3)difference_update()  symmetric_difference_update()

 

s1 ={11,22,33}
s2 ={22,33,44}
s1.difference_update(s2)  ## A存在 ,不不存在 ,更新到 A中
print (s1)

#以下为执行结果:
{11}

s1 ={11,22,33}
s2 ={22,33,44}
s1.symmetric_difference_update(s2)  #两个不同集合  ,更新到 A
print (s1)
#以下为执行结果:
{11,44}

 

          4)删除  discard(111) remove() pop() clear()

s1 = {11,22,33}
s1.remove(1111)#不存在,脚本会报错

#以下为执行结果
Traceback (most recent call last):
  File "1.py", line 3, in <module>
    s1.remove(1111)#不存在,脚本会报错

s1 = {11,22,33}
s1.discard(111)#不报错,写脚本是建议使用
print (s1)

#以下为执行结果
{33, 11, 22}

s1 = {11,22,33}
s1.pop()  #由于set是无序的,会随机移除 ,pop 不能加参数,不建议使用
print (s1)

#以下为执行结果

s1 = {11,22,33}
s1.clear()
print (s1)
#以下为执行结果
set()

 

          5)交集并集 :intersection()  union()

s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.intersection(s2)  #交集
print (s3)
s3 = s1.union(s2)  #并集
print (s3)
#以下为执行结果:
{33, 22}
{33, 22, 11, 44}

s1 = {11,22,33}
s2 = {22,33,44}
s1.intersection_update(s2)  #A和B的交集更新到A
print (s1)
#以下为执行结果:
{33, 22}

 

          6)批量添加 update()

s1 = {11,22,33}
li = [11,22,33,44]
s1.update(li) #传递一个迭代可以被for循环的对象   批量添加    添加list
print (s1)

#以下为执行结果
{33, 11, 44, 22}

           

二、函数

      1.创建函数

          格式:1) def

                  2) name

                  3) ()

                  4) return      

      2.参数

          1) 普通参数         

def send(xxoo, content):  #xxoo,content形参
    print (xxoo, content)
    print ("发送邮件成功:",xxoo,content)
    return True
send('alex','sb')      #'alex','NB'实参

 

          2) 指定参数

 

def send (xxoo,content):   
     print (xxoo,content)
     return True

send(content="alex", xxoo = "sb")#指定参数

 

          3) 默认参数

def send(xxoo,content,xx="ok"):#默认参数
    print(xxoo,countent,xx)
    return True
send('alex','sb')
send('alex','sb',"BB")

 

          4) 动态参数

 

#传多个函数 动态参数
#传列表:
def fl (*args):
    print (args, type(args))
li = [11,22,"alex","hhhh"]
fl(li)

#以下为执行结果:
([11, 22, 'alex', 'hhhh'],) <class 'tuple'>


def fl (*args):
    print (args, type(args))
li = [11,22,"alex","hhhh"]
fl(*li)

#以下为执行结果:
(11, 22, 'alex', 'hhhh') <class 'tuple'>

#传字典
def fl (**args):
print (args, type(args))
fl(n1="alex",n2=18)

#以下为执行结果:
{'n2': 18, 'n1': 'alex'} <class 'dict'>

def fl (**args):
print (args, type(args))
dic = {'k1':"v1", "k2":"v2"}
fl(**dic)

#以下为执行结果:
{'k1': 'v1', 'k2': 'v2'} <class 'dict'>

 

          5) 万能参数

 

def fl (*args, **kwargs):
    print (args)
    print (kwargs)

fl(11,22,33,44,k1 ="v1", k2 ="v2")

#以下为执行结果:
(11, 22, 33, 44)
{'k1': 'v1', 'k2': 'v2'}

 

       3.格式化

 

s1 = "i am {0},age {1}".format("alex",18)
print (s1)
s2 = "i am {0},age {1}".format(*["alex",18])

print (s2)

s1 = "i am {name},age {age}".format(name="alex",age=18)
print (s1)

dic = {'name':"alex","age":18}
s2 = "i am {name},age{age}".format(**dic)
print (s2)

#以下为运行结果:
i am alex,age 18
i am alex,age 18
i am alex,age 18
i am alex,age 18

 

     4.全局变量

# 全局变量,所有作用域都可读
# 对全局变量进行【重新赋值】,需要global
# 特殊:列表字典,可修改,不可重新赋值
NAME = None

def f1():
    age = 18
    global NAME # 表示,name是全局变量
    # NAME = "123"

    print(age, NAME)

def f2():
    age = 19
    print(age, NAME)
f1()
f2()

 

三、附加

         1) 三元运算(三目运算)

               

# 三元运算,三目运算
if  1 == 1:
    name  = "alex"
else:
    name  = "SB"

name = "alex" if 1==1 else "SB"  #简易的 if ...else 语句

print (name)

 

         2) lambda

def f1(a1):                              
    return a1 + 100

f2 = lambda a1,a2:a1 + a2 + 100 #简易的函数写法

 ret = f1(10) print(ret) print(f2(10,30))

 

四.内置函数

 Python所有的内置函数

  Built-in Functions  
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() __import__()
complex() hash() min() set() apply()
delattr() help() next() setattr() buffer()
dict() hex() object() slice() coerce()
dir() id() oct() sorted() intern()

      1.all() any()

n=all([1,2,3,4,0]) #所有都为真才为真
print (n)
#以下为执行结果:
False

n = any([[],1,2,]) #y有一个真 都为真
print (n)
#以下为执行结果:
True

      2.bin() oct() hex()

print (bin(5))   #十进制转二进制
#以下为执行结果:
0b101

print (oct(6))  #十进制转八进制
#以下为执行结果:
0o6

print (hex(5)) #十进制转十六进制
#以下为执行结果:
0x5

     3.bytes()

# utf-8 一个汉字:三个字节
# gbk 一个汉字:二个字节
# utf-8
s = "李杰"
# 一个字节8位,一个汉字三个字节
#  0101010 10101010 101010101  0101010 10101010 101010101
#     23     23      23           23     23      23  15
#     2f     2a      2c           2c     2e      2f  f
# 字符串转换字节类型
# bytes(只要转换的字符串, 按照什么编码)
n = bytes("李杰", encoding="utf-8")
print(n)
#以下为执行结果:
b'\xe6\x9d\x8e\xe6\x9d\xb0'

n = bytes("李杰", encoding="gbk")
print(n)
#以下为执行结果:
b'\xc0\xee\xbd\xdc'

# 字节转化成字符串
new_str = str(bytes("李杰", encoding="utf-8"), encoding="utf-8")
print (new_str)
#以下为执行结果:
#李杰

 

五、文件操作

     1.格式

             1) f=open(name[,mode[,buffering]]) #打开文件需要关闭文件

                 f.closed()  

             2) with open(name[,mode[,buffering]]) as f: #不需要关闭文件

     2.模式

打开文件的模式有:

r ,只读模式【默认】
w,只写模式【不可读;不存在则创建;存在则清空内容;】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读;   不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件

r+, 读写【可读,可写】
w+,写读【可读,可写】
x+ ,写读【可读,可写】
a+, 写读【可读,可写】
 "b"表示以字节的方式操作

rb  或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

    3.操作:

            1) read()  write() tell() close()

 #db文件内容 wudalang|123 
f = open('db','r+',encoding='utf-8') #如果打开方式无 b,则read,按照字符读取 data = f.read(1) print(data)print (f.tell()) #tell当前指针的位置 f.seek(f.tell()) #调整当前的指针 f.write("777") #当前指针位置开始向覆盖 f.close()

#以下为执行结果:
w
1
#cat db
w777lang|123

 

            2)  fileno()  

 

 

fo = open("db", "wb")               
print ("Name of the file:", fo.name)

fid = fo.fileno()        #此方法返回整数的底层实现使用请求从操作系统的I / O操作的文件描述符
print ("File Descriptor: ", fid) fo.close()

#以下为执行结果:

Name of the file: fooo.txt
File Descriptor:
3


            3) flush()  readline()  truncate()

# flush 强刷
# readline 仅读取一行
# truncate 截断,指针为后的清空

 

posted @ 2016-05-24 16:34  不是云  阅读(269)  评论(0编辑  收藏  举报