python study to 3 基础篇

集合(set)

Set集合定义:

     一个无序不重复可嵌套的数据集合。

Set集合创建的表示形式:

     S1 = {a1,a2,a3} #一般形式,使用一个大括号,大括号里面的元素使用逗号隔开。

     S2 = set () #创建一个空的集合

     S3 = set ([11,22,33]) #创建一个嵌套类表的集合

Set集合函数操作       

  1 class set(object):
  2  """
  3      set() -> new empty set object #创建一个空的集合
  4      set(iterable) -> new set object
  5      
  6      Build an unordered collection of unique elements.
  7      """
  8 定义两个集合:
  9  s1 = {11,22,33,}
 10  s2 = {22,33,44}
 11 def add(self, *args, **kwargs): # real signature unknown#给一个集合添加一个元素
 12     """
 13     Add an element to a set.
 14     
 15     This has no effect if the element is already present.
 16     """
 17    pass
 18 例如:
 19     给s1添加一个元素”a” 
 20     s1.add(“a”)
 21   
 22 def clear(self, *args, **kwargs): # real signature unknown #删除集合中所有元素
 23     """ Remove all elements from this set. """
 24     pass
 25 例如:
 26    删除s1中的所有元素
 27     s1.clear()
 28   
 29 def copy(self, *args, **kwargs): # real signature unknown 
 30     """ Return a shallow copy of a set. """  #通过复制一个集合创建一个新集合
 31     pass
 32 例如:
 33    复制s1中的元素创建一个新的集合snew
 34    Snew = s1.copy
 35   
 36 def difference(self, *args, **kwargs): # real signature unknown
 37     """ #A中存在,B中不存在;或者 B中存在,A中不存在 然后创建一个新集合
 38     Return the difference of two or more sets as a new set.
 39     
 40     (i.e. all elements that are in this set but not the others.)
 41     """
 42     pass
 43 例如:
 44     取s1中存在,s2中不存在 或者s2中存在,s1中不存在的元素,然后创建一个新集合
 45 Snew = s1.difference(s2) or Snew = s2.difference(s1)
 46      
 47 def difference_update(self, *args, **kwargs): # real signature unknown
 48     """ Remove all elements of another set from this set. """
 49     #取A集合中存在,B集合中不存在的元素然后更新到A集合中,注意:A集合中的其他元素被删除
 50     pass 
 51 例如:
 52    取s1集合中存在,s2集合中不存在的元素然后更新到s1集合中,然后s1中的其他元素删除
 53      s1.difference_update(s2)
 54   
 55 def discard(self, *args, **kwargs): # real signature unknown
 56     """ #移除集合中指定的某个元素
 57     Remove an element from a set if it is a member.
 58     
 59     If the element is not a member, do nothing.
 60     """
 61     pass
 62 例如:
 63     移除s1中的11元素
 64     s1.discard(11) 注意:移除集合中没有的元素也是不会报错的 如:s1.discard(1111)
 65   
 66 def intersection(self, *args, **kwargs): # real signature unknown
 67     """ #取两个集合总的并集,然后创建一个新集合
 68     Return the intersection of two sets as a new set.
 69     
 70     (i.e. all elements that are in both sets.)
 71     """
 72     pass
 73 例如:
 74   s1与s2的交集,然后生成一个snew新集合
 75   Snew = s1.intersection(s2)
 76   
 77 def intersection_update(self, *args, **kwargs): # real signature unknown
 78     """ Update a set with the intersection of itself and another. """
 79    #两个集合的交集相同元素,更新替换某一集合中的元素
 80     pass
 81 例如:
 82    s1与s2的交集相同元素,更新替换s1中的其他元素
 83    s1.intersection_update(s2)
 84      
 85 def isdisjoint(self, *args, **kwargs): # real signature unknown
 86     """ Return True if two sets have a null intersection. """
 87     #如果没有交集,返回True,否则返回False
 88     pass
 89 例如:
 90     判断s1与s2是否有交集,返回值为布尔值
 91     s1.isdisjoint(s2)
 92 
 93 def issubset(self, *args, **kwargs): # real signature unknown
 94     """ Report whether another set contains this set. """
 95    #判断一个集合是否是另一个集合的子序列
 96     pass
 97 例如:
 98     s1是否是s2子序列
 99     s1.issubset(s2)
100           
101 def issuperset(self, *args, **kwargs): # real signature unknown
102    """ Report whether this set contains another set. """
103     #判断一个集合是否是另一个集合的父序列
104    pass
105 例如:
106     判断s1是否是s2的父序列
107      s1.isuperset(s2)
108  
109 def pop(self, *args, **kwargs): # real signature unknown
110    """ #随机删除一个集中的元素
111    Remove and return an arbitrary set element.
112    Raises KeyError if the set is empty.
113    """
114    pass
115 例如:    
116     随机删除集合s1中的某个元素。注:此函数不经常使用
117     s1.pop()
118           
119 def remove(self, *args, **kwargs): # real signature unknown
120   """ #移除集合中指定的某个元素
121    Remove an element from a set; it must be a member.
122          
123    If the element is not a member, raise a KeyError.
124    """
125    pass
126 例如:
127   移除s1中的11
128   s1.remove(11) 注意:remove()在移除集合中没有存在的元素会报错,例如:s1.remove(1111)
129  
130 def symmetric_difference(self, *args, **kwargs): # real signature unknown
131    """ #对称差集,取两个集合中不同元素组成一个新集合
132    Return the symmetric difference of two sets as a new set.
133    
134    (i.e. all elements that are in exactly one of the sets.)
135    """
136    pass
137 例如:
138    把s1中存在,s2中不存在的 和 s2中存在的,s1中存在的元素组成一个新的集合
139    s1.symmetric_difference(s2)
140  
141 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
142    """ Update a set with the symmetric difference of itself and another. """
143    #对称差集,取两个集合中不同元素组成一个新集合,然后更新替换某个集合中的元素
144    pass
145 例如:
146     把s1中不存在和s2中不存在的元素组成一个新集合更新替换到s1
147     s1.symmetric_difference_update(s2)
148 
149 def union(self, *args, **kwargs): # real signature unknown
150    """
151    Return the union of sets as a new set.
152    #两个集合中的元素合并到一个新的集合中
153    (i.e. all elements that are in either set.)
154    """
155    pass
156 例如:
157     s1与s2两个集合的并集,产生一个新的集合
158     Snew = s1.union(s2)
159     
160 def update(self, *args, **kwargs): # real signature unknown
161   """ Update a set with the union of itself and others. """ 
162    #取两个集合并集更新一个集合
163   pass
164 例如:
165     s1与s2两个集合的并集,然后更新到s1中
166     s1.update(s2)  
View Code

函数(Function)

一、背景:

Python程序语言在开始学习的时,根据需求编写程序代码从上而下的实现需求功能,多个需求相同时,需要复制多个重复功能的代码,这种面向过程的显得代码非常冗长,比较乱,可读性比较差。

二、函数定义和使用:

函数定义标准语法:

def f1( parameters ):
  "函数_文档字符串"
   function_suite
   return [expression]

标准函数定义必要几部分:

def #定义函数必要的关键字
f1 #函数名,调用函数需要使用函数名
(parameters)#参数,为函数体提供需要处理的数据
function_suite #函数体在函数中执行一系列的逻辑元算
return[] #当函数执行完成后,返回一个逻辑运算处理的结果

函数中参数的分类:

1、实际参数

2、形式参数分类:

普通参数 #(严格按照顺序,将实际参数赋值给形式参数)
 默认参数 #(默认参数必须放置形式参数列表的最后)
 指定参数 #(将实际参数赋值给指定的形式参数)
 动态参数:
        *默认将传入的参数,全部放置在元组中  def f1(*[a,11.,b,c]) 输入类型为元组
       **默认将传入的参数,全部放置在字典中  def f1(**{k1:v1,k2:v2}) 输入类型为字典
 万能参数,*args,**kwargs   def f1(*args,**kwargs)

3、形式参数例子枚举:

1 #######定义函数######
2  def f1(name): #函数名为f1,f1后面括号中的name为此函数的形式参数,简称:形参
3       Print name
4 
5 ######调用函数######
6 f1(“abel”) #”abel”为调用f1函数的实际参数,简称:实参
普通参数枚举
1 def f1(name,age=23):
2      Print(“%s:%s”,%(name,age))
3 f1(“abel”,25) # 调用函数式指定参数
4 f1(“jack”) #调用函数式使用默认参数
默认参数和指定参数
 1 def f1(*args):
 2      Print args
 3 f1(11,22,33,44,) #调用函数输出为一个(11, 22, 33, 44)把输入的4个数字作为元组中的元素输入
 4 f1([11,22,33,44,])#调用函数输出为一个([11, 22, 33, 44],)把如输入的列表作为元组中的一个元素输入
 5 List=[11,22,33,44,]
 6 f1(*list) #调用函数输出为一个(11, 22, 33, 44)把输入的一个列表中4个元素转换为元组中的4个元素输入。
 7 
 8 def f1(**kwargs): 
 9      Print args
10 f1(name = “alex”,age=33) #
11 list = {“name”:”alex”,age:18,”gender”:”male”}
12 f1(**list)
动态参数
1 def f1(*args,**kwargs): #万能参数
2      Print args
3      Print kwargs
4 dic1 = {“name”:”alex”,age:18,”gender”:”male”}
5 list1 = [11,22,33,44]
6 Str1 = “jack”
7 f1(*list1,**dic1) # **传入一个键值对给函数体。
8 f1(*str1) # 字符串按照每个字符意义输入。
万能参数

 4、函数返回值

def f1():
   Print(123)
   Return “111” #在函数中执行到return 函数就代表执行完成,return下面的语句不会执行。
   Print (456)
r = f1()
Print(r)

def f2():
     Print(123)

r = f2() #如果函数体中没有return,函数则返回None
Print (r)

5、补充:函数传值使用方式以及全局变量的作用域

 1 函数传值是引用这个值而不是重新复制一份。
 2 def f1(a1):
 3     a1.append(99)
 4 
 5 li=[11,22,33,44]
 6 f1(li)
 7 print(li)
 8 
 9 全局变量:
10 不在任何的函数体内,任何函数都使用全局变量,在函数体内定义全局变量需要使用global关键字,函数体内给全局变量重新赋值需要使用global关键字。全局变量名书写形式使用大写。
11 
12 NAME="WANG"
13 def f1():
14     global NAME;NAME="li"  #使用关键字修改全局变量。
15     age=18
16     print(age,NAME)
17 
18 def f2():
19     age=19
20     print(age,NAME)
21 f1();f2()
View Code

lambda表达式

三元运算,三目运算,针对if else 语句的表示形式,如:

普通条件语句:
If a == a:
     Name = “jack”
Else:
     Name = “eric
#三元运算
 Name =”jack” if a == a else “eric”  #如果if条件成立(true),Name="jack",否则Name="eric"。

针对函数lambda表达式,如:

# ##########普通函数##########
# 定义函数(普通函数)
Def f1(a1):
     Return a1+3

执行函数
Ret = f1(10)

改写成:
f1=lambda a1 : a1+3 #针对简单函数的表达方式。
# ##########lambda########## # 定义函数(lambda表达式) F1_lambda = lambda a1 : a1 + 1 # 执行函数 Ret = f1_lambda(10)

python内置函数

1、bool() False 值有0,none,空字符串,其他都为True
print(bool(1))

2、#all方法中传入可迭代对象中只要包含0,none,空字符串,则返回值为False
n=all([1,2,3,""])
print(n)

3、#any方法中传入可迭代的对象中只要一个为真,则返回一个为真的值。
m=all([0,0,"",None])
print(m)

4、#ascii() 自动执行对象的__repr__方法
class Foo:
    def __repr__(self):
        return "111"

obj1=Foo()
n=ascii(obj1)
print(n)

5、print(bin(5)) #十进制转换成二进制
6、print(oct(5)) #十进制转换成八进制
7、print(hex(5)) #十进制转换成16进制

8、#utf-8编码 一个汉字三个字节,gbk编码一个汉字两个字节
# 字符串转换字节类型,使用bytes()函数
# 例如:
m="王刚"
n=bytes(m,encoding="utf8")
print(n)

n=bytes(m,encoding="gbk")
print(n)

# 字节转换成字符串
s="小明"
k=bytes(s,encoding="utf-8")
s=str(k,encoding="utf-8")
print(s)

1、callable()  #判断(函数)是否能够被执行或者被调用,此函数返回值为 Ture or False
   def f1():
     pass
   print(callable(f1))
2、chr()  #把数字转换成ASCII字符
   print(chr(65))
3、ord()  #把ASCII字符串转换成对应的数字
   print (ord(","))
4、randrange()  #需要导入 import random模块,此函数产生随机数
   I=Import rand.range(3,5)
   Print(i)
5、compile(s, "<string>","exec")  #把一个字符串编译成python代码
    m="梁怀军"
    s= "print(m)"
    r = compile(s,"<string>","exec")
    print(r)
exec(r)
6、eval()  把字符串转换成python表达式, python执行表达式 获取返回值
s= "8*8"
r=eval(s)
print(r)
7、exec()  #执行python 代码或者字符串,exec()没有返回值

8、dir()  #快速查看一个对象提供了那些功能
    print(dir(dict))
9、help()  #帮忙查找一个对象的操作源码
    Help(dict)
10、filter(函数,可迭代的对象)  #筛选,符合条件有返回值,不符合条件的没有返回值
def f2(a):
    if a > 22:
return True
     li = [11,22,33,44,55]
      # filter 内部循环第二个参数
      # result = []
      # for item in 第二个参数:
      # r = 第一个参数(item)
      # if r:
      # result()
      # return result
      # filter
     ret = filter(f2,li) #循环第二个参数,让每个循环元素执行函数,如果函数返回值为True,表示合法元素。
     print(list(ret))
Lambda的书写方式:
li = [11,22,33,44,55]
ret = filter(lambda a:a > 33 ,li)
print(list(ret))


11、Map(函数,可迭代的对象(可for循环的数据类型))
    li = [11, 22, 33, 44, 55]
    def f2(a):
      return a + 100
result = map(f2, li)
Print(list(result))
  使用lambda表达式的表示方法:
   result = map(lambda a: a + 200, li)
   print(list(result))
注意:filter与map的本质区别
     Filter : 函数返回True,将元素添加到结果中
     Map:  将函数返回值添加到结果中
12、globals()  #定义所有的全局变量
13、Locals()   #定义所有的局部变量
14、Hash()  #转换成哈希值,一般用于字典的key来保存
     s = "王刚"
     print(hash(s))
15、len()  #测试字符串长度
# python 3里默认按字符()
s = "李杰"
print(len(s))
# 字节长度,python2.7里默认按字节
s = "李杰"
b = bytes(s, encoding="utf-8")
print(len(b))
16、sum()  #求和函数
     s = [11,22,33,44]
     print(sum(s))
17、pow()  #求某个数的多少次方
S = pow(2,10)
Print(s)
18、slince()  #切片函数
     s = "sssssssss"
     print(s[0:2:2])
19、sorted()  #对有序数据类型进行排序(包括:列表、元组、字符串)
li = (11,22,33,1,5,8,)
s =sorted(li)
print(s,type(s))

20、round()  #四舍五入
Round(1.4)

21、zip()  #把相同数据类型的相同位置的元素组成一个元素
     l1 = ["alex", 11, 22, 33, ]
     l2 = ["is", 11, 22, 33, ]
     l3 = ["nb", 11, 22, 33, ]
     r = zip(l1, l2, l3)
     # print(list(r))
     temp = list(r)[0]
     ret = " ".join(temp)
     print(ret)
内置函数操作

文件操作

Open()函数,此函数用于文件的操作打开

文件操作流程:

 打开文件

 操作文件

 关闭文件

一、打开文件

文件打开语法:

 f = open(文件路径,文件打开模式)
打开文件时,需要指定文件路径和文件打开方式,打开后,即可获取文件句柄,文件的操作使用文件句柄来操作。

文件打开模式:

 r 只读模式(默认)

 w 只写模式(不可读;文件不存在则先创建文件;文件存在的清空文件内容)

 x 只写模式(不可读;文件不存在则先创建文件;文件存在的报错)#python3中已经被遗弃

 a,追加模式(文件可读;文件不存在则先创建文件;文件存在可在文件中追加内容)#python3中文件不可读,但可写

 

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

 r+  读写(可读、可写)

w+  写读(可读、可写)

 x+  写读(可读、可写) #python3已经被遗弃

a+  写读(可读、可写)

 

“b”表示以字节的方式操作

  • rb 或 r+b 文件可读可写
  • wb 或 w+b 文件可读可写
  • ab 或 a+b 文件可读可写

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

二、文件操作

文件操作函数:

F.read() #无参数读取全部文件;有参数 b,按字节读取,无b,按字符读取
F.tell() #获取当前指针的位置(字节指针位置)
F.seek() #指针跳转指定位置
F.write() #写入文件数据,有参数b,数据以字节形式写入,无参数b,数据以字符形式写入
F.close() #文件操作完成关闭文件动作
F.fileno() #文件描述
F.flush() #刷新文件内部缓冲区
F.readline() #文件逐行读取
F.truncate() #截取数据,仅保留指定之前数据

三、文件关闭

文件关闭语法:

f.close()

文件关闭的两种方式:

f.close() #关闭文件。
with open(“filename”) as f: #使用with 打开一个文件,文件处理完成后自动关闭。
with open("mm","r",encoding="utf-8") as f1,open("kk","r+",encoding="utf-8") as f2:
    time=0
    for line in f1:
        if time<=5:
            time+=1
            f2.write(line+"\n")
        else:
            break
案例:一个文件读写入另一个文件
f=open("db","r+",encoding="utf-8")
#如果打开模式无b,则read,按照字符读取,
data=f.read(1) #如果括号内有值,指针移动到指定的位置,如果无值则指针移动到文件最后位置。
#tell 当前指针所在的位置(字节)
print(f.tell())
#调整当前指针你的位置(字节)
f.seek(f.tell())
#当前指针位置开始向后覆盖
f.write("9999")
print(f.tell())
f.close()
案例:文件指针操作
#flush()强刷
f=open("db","a",encoding="utf-8")
f.write("123")
f.flush() #如果文件没有关闭的情况下,f.write()是不会写入文件的,如果想要随时写入磁盘,必须执行f.flush()刷新函数。
input("abc")
案例:文件刷新案例
# truncate 截断,指针为后的清空
f=open("db","r+",encoding="utf-8")
f.seek(3)
f.truncate()
f.close()
truncate文件截断
f=open("db","w")
m=f.readable()
print(m) 布尔值

f=open("db","w")
m=f.writable()
print(m)
判断文件是否可读写

字符串格式化:

 1 format(*args)
 2 s1="i am {0},age{1}".format("alex",18)
 3 print(s1)
 4 s2="i am {0},age{1}".format(*["alex",18])  #直接传入列表
 5 print(s2)
 6 
 7 format(**args)
 8 s1="i am {name},age{age}".format(name="alex",age=18)
 9 print(s1)
10 dict={"name":"alex","age":18,}
11 s2="i am {name},age{age}".format(**dict)  #直接字典形式
12 print(s2)
format字符串格式化

 

 

  

 

 

 

 

 

 

  

 

 

 

 

posted @ 2016-05-24 09:30  梁怀军  阅读(216)  评论(0编辑  收藏  举报