python study to 3 基础篇

本文详细介绍了Python中集合(Set)的基本概念、创建方法及常用操作函数,并深入探讨了Python函数的定义、使用方法、参数传递及返回值等关键知识点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

集合(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 # python 内置函数
 2 
 3 # abc() 绝对值函数
 4 
 5 # all() all里面可被迭代的对象所有为真则为真
 6 
 7 # any() 任何为真则为真
 8 
 9 # ascii()自动执行对象的_repr
10 
11 # bin()十进制转换成二进制
12 
13 # oct()十进制转换成八进制
14 
15 # hex()十进制转换成十六进制
16 
17 # chr() 十进制数转换成ascii
18 
19 #ord() 字符转换成十进制数
View Code

字符编码中 utf-8使用三个字节来表示,gbk使用两个字节来表示。

字符串转换成字节类型:

Name=王刚
Bytes(字符串str,按照**编码)如:
name = "王刚"
byt = bytes(name,encoding="utf-8")
print(byt,type(byt))

字节转换成字符串类型:

Str(字节bytes,按照**编码)如:
name = "王刚"
byt = bytes(name,encoding="utf-8")
str1 = str(byt,encoding="utf-8")
print(str1,type(str1))

文件操作

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

文件操作流程:

 打开文件

 操作文件

 关闭文件

一、打开文件

文件打开语法:

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

文件打开模式:

u r 只读模式(默认)

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

u X 只写模式(不可读;文件不存在则先创建文件;文件存在的报错)

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

 

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

v r+  读写(可读、可写)

v w+  写读(可读、可写)

v x+  写读(可读、可写)

v a+  写读(可读、可写)

 

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

  • rb 或 r+b
  • wb 或 w+b
  • xb 或 x+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 打开一个文件,文件处理完成后自动关闭。

字符串格式化:

 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字符串格式化

 

 

  

 

 

 

 

 

 

  

 

 

 

 

转载于:https://www.cnblogs.com/huaijunliang/p/5522319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值