Python高手之路python基础之函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python高手之路python基础之函数相关的知识,希望对你有一定的参考价值。
基本数据类型补充:
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 def add(self, *args, **kwargs): # real signature unknown
9 """
10 Add an element to a set,添加元素
11
12 This has no effect if the element is already present.
13 """
14 pass
15
16 def clear(self, *args, **kwargs): # real signature unknown
17 """ Remove all elements from this set. 清除内容"""
18 pass
19
20 def copy(self, *args, **kwargs): # real signature unknown
21 """ Return a shallow copy of a set. 浅拷贝 """
22 pass
23
24 def difference(self, *args, **kwargs): # real signature unknown
25 """
26 Return the difference of two or more sets as a new set. A中存在,B中不存在
27
28 (i.e. all elements that are in this set but not the others.)
29 """
30 pass
31
32 def difference_update(self, *args, **kwargs): # real signature unknown
33 """ Remove all elements of another set from this set. 从当前集合中删除和B中相同的元素"""
34 pass
35
36 def discard(self, *args, **kwargs): # real signature unknown
37 """
38 Remove an element from a set if it is a member.
39
40 If the element is not a member, do nothing. 移除指定元素,不存在不保错
41 """
42 pass
43
44 def intersection(self, *args, **kwargs): # real signature unknown
45 """
46 Return the intersection of two sets as a new set. 交集
47
48 (i.e. all elements that are in both sets.)
49 """
50 pass
51
52 def intersection_update(self, *args, **kwargs): # real signature unknown
53 """ Update a set with the intersection of itself and another. 取交集并更更新到A中 """
54 pass
55
56 def isdisjoint(self, *args, **kwargs): # real signature unknown
57 """ Return True if two sets have a null intersection. 如果没有交集,返回True,否则返回False"""
58 pass
59
60 def issubset(self, *args, **kwargs): # real signature unknown
61 """ Report whether another set contains this set. 是否是子序列"""
62 pass
63
64 def issuperset(self, *args, **kwargs): # real signature unknown
65 """ Report whether this set contains another set. 是否是父序列"""
66 pass
67
68 def pop(self, *args, **kwargs): # real signature unknown
69 """
70 Remove and return an arbitrary set element.
71 Raises KeyError if the set is empty. 移除元素
72 """
73 pass
74
75 def remove(self, *args, **kwargs): # real signature unknown
76 """
77 Remove an element from a set; it must be a member.
78
79 If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
80 """
81 pass
82
83 def symmetric_difference(self, *args, **kwargs): # real signature unknown
84 """
85 Return the symmetric difference of two sets as a new set. 对称差集
86
87 (i.e. all elements that are in exactly one of the sets.)
88 """
89 pass
90
91 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
92 """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
93 pass
94
95 def union(self, *args, **kwargs): # real signature unknown
96 """
97 Return the union of sets as a new set. 并集
98
99 (i.e. all elements that are in either set.)
100 """
101 pass
102
103 def update(self, *args, **kwargs): # real signature unknown
104 """ Update a set with the union of itself and others. 更新 """
105 pass
1:创建
1 s = set()
2 s = {11,22,33,55}
2:转换
1 li = [11,22,33,44]
2 tu = (11,22,33,44)
3 st = ‘123‘
4 s = set(li)
3:intersection , intersection_update方法
a = {11,22,33,44}
b = {22,66,77,88}
ret = a.intersection(b)
print(ret)
intersection取得两个集合中的交集元素,并将这些元素以一个新的集合返回给一个变量接收
a = {11,22,33,44}
b = {22,66,77,88}
a.intersection_update(b)
print(a)
intersection_update取得两个集合的交集元素,并更新a集合
4:isdisjoint , issubset , issuperset方法
1 s = {11,22,33,44}
2 b = {11,22,77,55}
3 ret = s.isdisjoint(b)#有交集返回False,没有交集返回True
4 print(ret)
5 ## False
issubset判断是否为子集
a = {11,22,33,44} b = {11,44} ret = b.issubset(a) print(ret) ########################################## True
issuperset判断是否为父集
a = {11,22,33,44} b = {11,44} ret = a.issubset(b) print(ret) ########################################## False
5:discard , remove , pop
1 s = {11,22,33,44}
2 s.remove(11)
3 print(s)
4 s.discard(22)
5 print(s)
6 s.pop()
7 print(s)
三者都能达到移除元素的效果,区别在于remove移除集合中不存在的元素时会报错,discard移除不存在的元素是不会报错,pop无法精确控制移除哪个元素,按其自身的规则随机移除元素,返回被移除的元素,可以使用变量接收其返回值
6:symmetric_difference取差集
1 s = {11,22,33,44}
2 b = {11,22,77,55}
3 r1 = s.difference(b)
4 r2 = b.difference(s)
5 print(r1)
6 print(r2)
7 ret = s.symmetric_difference(b)
8 print(ret)
9 ## set([33, 44])
10 ## set([77, 55])
11 ## set([33, 44, 77, 55])
symmetric_difference返回两个集合中不是交集的元素
上面的代码中,将symmetric_difference换成symmetric_difference_update则表示将两个集合中不是交集的部分赋值给s
7:union , update方法
1 s = {11,22,33,44}
2 b = {11,22,77,55}
3 ret = s.union(b)
4 print(ret)
5 ## set([33, 11, 44, 77, 22, 55])
union方法合并两个集合
1 s = {11,22,33,44}
2 b = {11,22,77,55}
3 s.update(b)
4 print(s)
5 ## set([33, 11, 44, 77, 22, 55])
update方法更新s集合,将b集合中的元素添加到s集合中!update方法也可以传递一个列表,如:update([23,45,67])
练习题:有下面两个字典
要求:
1)两个字典中有相同键的,则将new_dict中的值更新到old_dict对应键的值
2)old_dict中存在的键且new_dict中没有的键,在old_dict中删除,并把new_dict中的键值更新到old_dict中
3)最后输出old_dict
1 # 数据库中原有
2 old_dict = {
3 "#1":{ ‘hostname‘:‘c1‘, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 },
4 "#2":{ ‘hostname‘:‘c1‘, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 },
5 "#3":{ ‘hostname‘:‘c1‘, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 }
6 }
7
8 # cmdb 新汇报的数据
9 new_dict = {
10 "#1":{ ‘hostname‘:‘c1‘, ‘cpu_count‘: 2, ‘mem_capicity‘: 800 },
11 "#3":{ ‘hostname‘:‘c1‘, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 },
12 "#4":{ ‘hostname‘:‘c2‘, ‘cpu_count‘: 2, ‘mem_capicity‘: 80 }
13 }
三元运算
三元运算(三目运算),是对简单的条件语句的缩写。
1 # 书写格式
2 result = 值1 if 条件 else 值2
3 # 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量
1 a = 1
2 name = ‘poe‘ if a == 1 else ‘jet‘
3 print(name)
深浅拷贝
一、数字和字符串
对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。
1 import copy
2 # ######### 数字、字符串 #########
3 n1 = 123
4 # n1 = "i am alex age 10"
5 print(id(n1))
6 # ## 赋值 ##
7 n2 = n1
8 print(id(n2))
9 # ## 浅拷贝 ##
10 n2 = copy.copy(n1)
11 print(id(n2))
12
13 # ## 深拷贝 ##
14 n3 = copy.deepcopy(n1)
15 print(id(n3))
二、其他基本数据类型
对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。
1、赋值
赋值,只是创建一个变量,该变量指向原来内存地址,如:
1 n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
2
3 n2 = n1
2、浅拷贝
浅拷贝,在内存中只额外创建第一层数据
1 import copy
2
3 n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
4
5 n3 = copy.copy(n1)
3、深拷贝
深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)
1 import copy
2
3 n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
4
5 n4 = copy.deepcopy(n1)
函数
1:函数的定义
def 函数名(参数):
...
函数体
...
返回值
函数的定义主要有如下要点:
def:表示函数的关键字
函数名:函数的名称,日后根据函数名调用函数
函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
参数:为函数体提供数据
返回值:当函数执行完毕后,可以给调用者返回数据。
2:返回值
函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。
以上要点中,比较重要有参数和返回值:
def 发送短信():
发送短信的代码...
if 发送成功:
return True
else:
return False
while True:
# 每次执行发送短信函数,都会将返回值自动赋值给result
# 之后,可以根据result来写日志,或重发等操作
result = 发送短信()
if result == False:
记录日志,短信发送失败...
3:参数
函数有三种不同的参数:
普通参数
# ######### 定义函数 #########
# name 叫做函数func的形式参数,简称:形参
def func(name):
print name
# ######### 执行函数 #########
# ‘wupeiqi‘ 叫做函数func的实际参数,简称:实参
func(‘poe‘)
默认参数
def func(name, age = 18):
print "%s:%s" %(name,age)
# 指定参数
func(‘poe‘, 19)
# 使用默认参数
func(‘gin‘)
注:默认参数需要放在参数列表最后
动态参数
def f1(*a):
print(a,type(a))
f1(123,456,[1,2,3],‘who‘)
## ((123, 456, [1, 2, 3], ‘who‘), <type ‘tuple‘>)
def func(**kwargs):
print args
# 执行方式一
func(name=‘poe‘,age=18)
# 执行方式二
li = {‘name‘:‘poe‘, age:18, ‘gender‘:‘male‘}
func(**li)
def f1(*a,**b) :#一个星的参数必须在前,两个星的参数必须在后
print(a,type(a))
print(b,type(b))
f1(11,22,33,k1=1234,k2=456)
## ((11, 22, 33), <type ‘tuple‘>)({‘k2‘: 456, ‘k1‘: 1234}, <type ‘dict‘>)
为动态参数传入列表,元组,字典:
def f1(*args) :
print(args,type(args))
li = [1,2,3,4]
f1(li)
f1(*li)
## (([1, 2, 3, 4],), <type ‘tuple‘>)
## ((1, 2, 3, 4), <type ‘tuple‘>)
def f2(**kwargs) :
print(kwargs,type(kwargs))
dic = {‘k1‘:123,‘k2‘:456}
f2(k1 = dic)
f2(**dic)
## ({‘k1‘: {‘k2‘: 456, ‘k1‘: 123}}, <type ‘dict‘>)
## ({‘k2‘: 456, ‘k1‘: 123}, <type ‘dict‘>)
4:内置函数
注:查看详细猛击这里
以上是关于Python高手之路python基础之函数的主要内容,如果未能解决你的问题,请参考以下文章