学习Python低手之路【三】python基础之函数

基本数据类型补充:


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

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 = ''
  4. s = set(li)

3:intersection , intersection_update方法

 
  1. a = {11,22,33,44}
  2. b = {22,66,77,88}
  3. ret = a.intersection(b)
  4. print(ret)

intersection取得两个集合中的交集元素,并将这些元素以一个新的集合返回给一个变量接收

 
  1. a = {11,22,33,44}
  2. b = {22,66,77,88}
  3. a.intersection_update(b)
  4. 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判断是否为子集

 
  1. a = {11,22,33,44}
  2. b = {11,44}
  3. ret = b.issubset(a)
  4. print(ret)
  5. ##########################################
  6. True

issuperset判断是否为父集

 
  1. a = {11,22,33,44}
  2. b = {11,44}
  3. ret = a.issubset(b)
  4. print(ret)
  5. ##########################################
  6. 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. # cmdb 新汇报的数据
  8. new_dict = {
  9. "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
  10. "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
  11. "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }
  12. }
 
  1. old_keys = set(old_dict.keys())
  2. new_keys = set(new_dict.keys())
  3. #需要更新元素的键
  4. update_keys = old_keys.intersection(new_keys)
  5. print(update_keys)
  6. #需要删除元素的键
  7. del_keys = old_keys.difference(new_keys)
  8. #需要添加元素的键
  9. add_keys = new_keys.difference(old_keys)
  10. print(del_keys)
  11. print(add_keys)
  12. update_keys = list(update_keys)
  13. for i in update_keys :
  14. old_dict[i] = new_dict[i]
  15. del_keys = list(del_keys)
  16. for j in del_keys :
  17. del old_dict[j]
  18. for k in list(add_keys) :
  19. old_dict[k] = new_dict[k]
  20. print(old_dict)
  21. ########################################
  22. {'#3': {'hostname': 'c1', 'cpu_count': , 'mem_capicity': }, '#1': {'hostname': 'c1', 'cpu_count': , 'mem_capicity': }, '#4': {'hostname': 'c2', 'cpu_count': , 'mem_capicity': }}

答案

collections系列

一、计数器(counter)

Counter是对字典类型的补充,用于追踪值的出现次数。

ps:具备字典的所有功能 + 自己的功能

 
  1. c = Counter('abcdeabcdabcaba')
  2. print c
  3. 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Counter

二、有序字典(orderedDict )

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

OrderedDict

三、默认字典(defaultdict) 

defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。

defaultdict

使用方法:

 
  1. import collections
  2. dic = collections.defaultdict(list)
  3. dic['k1'].append('alext')
  4. print(dic)

练习:

 
  1. 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
  2. 即: {'k1': 大于66 , 'k2': 小于66}
 
  1. values = [11, 22, 33,44,55,66,77,88,99,90]
  2. my_dict = {}
  3. for value in values:
  4. if value>66:
  5. if my_dict.has_key('k1'):
  6. my_dict['k1'].append(value)
  7. else:
  8. my_dict['k1'] = [value]
  9. else:
  10. if my_dict.has_key('k2'):
  11. my_dict['k2'].append(value)
  12. else:
  13. my_dict['k2'] = [value]

原生字典

 
  1. from collections import defaultdict
  2. values = [11, 22, 33,44,55,66,77,88,99,90]
  3. my_dict = defaultdict(list)
  4. for value in values:
  5. if value>66:
  6. my_dict['k1'].append(value)
  7. else:
  8. my_dict['k2'].append(value)
  9. defaultdict字典解决方法
  10. 默认字典

默认字典

四、可命名元组(namedtuple) 

根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。

Mytuple

五、双向队列(deque)

一个线程安全的双向队列

deque

注:既然有双向队列,也有单项队列(先进先出 FIFO )

Queue.Queue

三元运算


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

 
  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. n3 = copy.deepcopy(n1)
  14. print(id(n3))

二、其他基本数据类型

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

1、赋值

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

 
  1. n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
  2. n2 = n1

2、浅拷贝

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

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

 

3、深拷贝

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

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

函数


1:函数的定义

 
  1. def 函数名(参数):
  2. ...
  3. 函数体
  4. ...
  5. 返回值

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

def:表示函数的关键字
函数名:函数的名称,日后根据函数名调用函数
函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
参数:为函数体提供数据
返回值:当函数执行完毕后,可以给调用者返回数据。

2:返回值

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

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

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

3:参数

函数有三种不同的参数:

普通参数

 
  1. # ######### 定义函数 #########
  2. # name 叫做函数func的形式参数,简称:形参
  3. def func(name):
  4. print name
  5. # ######### 执行函数 #########
  6. # 'wupeiqi' 叫做函数func的实际参数,简称:实参
  7. func('poe')

默认参数

 
  1. def func(name, age = 18):
  2. print "%s:%s" %(name,age)
  3. # 指定参数
  4. func('poe', 19)
  5. # 使用默认参数
  6. func('gin')
  7. 注:默认参数需要放在参数列表最后

动态参数

 
  1. def f1(*a):
  2. print(a,type(a))
  3. f1(123,456,[1,2,3],'who')
  4. ## ((123, 456, [1, 2, 3], 'who'), <type 'tuple'>)
 
  1. def func(**kwargs):
  2. print args
  3. # 执行方式一
  4. func(name='poe',age=18)
  5. # 执行方式二
  6. li = {'name':'poe', age:18, 'gender':'male'}
  7. func(**li)
 
  1. def f1(*a,**b) :#一个星的参数必须在前,两个星的参数必须在后
  2. print(a,type(a))
  3. print(b,type(b))
  4. f1(11,22,33,k1=1234,k2=456)
  5. ## ((11, 22, 33), <type 'tuple'>)({'k2': 456, 'k1': 1234}, <type 'dict'>)

为动态参数传入列表,元组,字典:(注:这几种数据类型在函数传参的时候只有引用传递,没有值传递

 
  1. def f1(*args) :
  2. print(args,type(args))
  3. li = [1,2,3,4]
  4. f1(li)
  5. f1(*li)
  6. ## (([1, 2, 3, 4],), <type 'tuple'>)
  7. ## ((1, 2, 3, 4), <type 'tuple'>)
 
  1. def f2(**kwargs) :
  2. print(kwargs,type(kwargs))
  3. dic = {'k1':123,'k2':456}
  4. f2(k1 = dic)
  5. f2(**dic)
  6. ## ({'k1': {'k2': 456, 'k1': 123}}, <type 'dict'>)
  7. ## ({'k2': 456, 'k1': 123}, <type 'dict'>)

4:内置函数

注:查看详细猛击这里

数据类型转换函数

  1. chr(i) 函数返回ASCII码对应的字符串
  2.  
      
    1. print(chr(65))
    2. print(chr(66))
    3. print(chr(65)+chr(66))
    4. ##########################################
    5. A
    6. B
    7. AB
  3. complex(real[,imaginary]) 函数可把字符串或数字转换为复数
  4.  
      
    1. print(complex("2+1j"))
    2. print(complex(""))
    3. print(complex(2,1))
    4. ##########################################
    5. (2+1j)
    6. (2+0j)
    7. (2+1j)
  5. float(x) 函数把一个数字或字符串转换成浮点数
  6.  
      
    1. print(float(12))
    2. print(float(12.2))
    3. ##########################################
    4. 12.0
    5. 12.2
  7. long(x[,base]) 函数把数字和字符串转换成长整数,base为可选的基数
  8. list(x) 函数可将序列对象转换成列表
  9. min(x[,y,z...]) 函数返回给定参数的最小值,参数可以为序列
  10. max(x[,y,z...]) 函数返回给定参数的最大值,参数可以为序列
  11. ord(x) 函数返回一个字符串参数的ASCII码或Unicode值
  12.  
      
    1. print(ord('a'))
    2. print(ord(u"A"))
    3. ##########################################
    4. 97
    5. 65
  13. str(obj) 函数把对象转换成可打印字符串
  14. tuple(x) 函数把序列对象转换成tuple
  15. type(x) 可以接收任何东西作为参数――并返回它的数据类型。整型、字符串、列表、字典、元组、函数、类、模块,甚至类型对象都可以作为参数被 type 函数接受

abs()函数:取绝对值

 
  1. print(abs(-1.2))

all()函数与any函数:

all(iterable):如果iterable的任意一个元素为0、''、False,则返回False,否则返回True

 
  1. print(all(['a','b','c','d']))#True
  2. print(all(['a','b','','d']))#False
  3. #注意:空元组、空列表返回值为True,这里要特别注意

any(iterable):如果iterable的所有元素都为0、''、False,则返回False,否则返回True

 
  1. print(any(['a','b','c','d']))#True
  2. print(any(['a',0,' ',False]))#True
  3. print(any([0,'',False]))#False

ascii(object) 函数:

返回一个可打印的对象字符串方式表示,如果是非ascii字符就会输出\x,\u或\U等字符来表示。与python2版本里的repr()是等效的函数。

 
  1. print(ascii(1))
  2. print(ascii('a'))
  3. print(ascii(123))
  4. print(ascii('中文'))#非ascii字符
  5. ##########################################
  6. 1
  7. 'a'
  8. 123
  9. '\u4e2d\u6587'

lambda表达式:

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

 
  1. # 普通条件语句
  2. if 1 == 1:
  3. name = 'poe'
  4. else:
  5. name = 'bruce'
  6. # 三元运算
  7. name = 'poe' if 1 == 1 else 'bruce'

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

 
  1. # ###################### 普通函数 ######################
  2. # 定义函数(普通方式)
  3. def func(arg):
  4. return arg + 1
  5. # 执行函数
  6. result = func(123)
  7. # ###################### lambda ######################
  8. # 定义函数(lambda表达式)
  9. my_lambda = lambda arg : arg + 1
  10. # 执行函数
  11. result = my_lambda(123) 

生成随机数:

 
  1. import random
  2. chars = ''
  3. for i in range(4) :
  4. rand_num = random.randrange(0,4)
  5. if rand_num == 3 or rand_num == 1:
  6. rand_digit = random.randrange(0,10)
  7. chars += str(rand_digit)
  8. else:
  9. rand_case = random.randrange(65,90)
  10. case = chr(rand_case)
  11. chars += case
  12. print(chars)

filter函数

filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

例1,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:

 
  1. # filter(fn,iterable)
  2. def is_odd(x) :
  3. return x % 2 == 1
  4. li = [1, 4, 6, 7, 9, 12, 17]
  5. result = filter(is_odd,li)
  6. print(result)
  7. ##########################################
  8. [1, 7, 9, 17] 

例2:删除 列表中的None 或者空字符串

 
  1. li = ['test', None, '', 'str', ' ', 'END']
  2. def is_not_empty(s) :
  3. return s and len(s.strip()) > 0
  4. print(filter(is_not_empty,li))
  5. ##########################################
  6. ['test', 'str', 'END']

例3:请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 
  1. import math
  2. def is_sqr(x) :
  3. return math.sqrt(x) % 1 == 0
  4. print filter(is_sqr,range(1,101))

以上三个函数都可以使用lambda表达式的写法来书写,如:

 
  1. result = filter(lambda x : x % 2 == 1,[1,4,6,9,12,7,17])
  2. print(result)

map()函数

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回

例如,对于list [1, 2, 3, 4, 5, 6, 7, 8, 9]如果希望把list的每个元素都作平方,就可以用map()函数

 
  1. li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  2. print(li)
  3. def f(x) :
  4. return x*x
  5. r = list(map(f,[1, 2, 3, 4, 5, 6, 7, 8, 9]))
  6. print(r)

注:在python3里面,map()的返回值已经不再是list,而是iterators, 所以想要使用,只用将iterator 转换成list 即可, 比如 list(map()) 。

进制转换函数(以下四个函数可以实现各进制间的互相转换)

bin(x) :将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer

oct(x):将一个整数转换成8进制字符串。如果传入浮点数或者字符串均会报错

hex(x):将一个整数转换成16进制字符串。

int():

  • 传入数值时,调用其__int__()方法,浮点数将向下取整
  •  
      
    1. print(int(3))#
    2. print(int(3.6))#
  • 传入字符串时,默认以10进制进行转换
  •  
      
    1. print(int(''))#
  • 字符串中允许包含"+"、"-"号,但是加减号与数值间不能有空格,数值后、符号前可出现空格
  •  
      
    1. print(int('+36'))#
  • 传入字符串,并指定了进制,则按对应进制将字符串转换成10进制整数
  •  
      
    1. print(int('',2))#
    2. print(int('0o7',8))#
    3. print(int('0x15',16))#

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

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

  1. 打开文件
  2. 操作文件

一:打开文件

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

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

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
 
  1. f = open('test.log','r')
  2. data = f.read()
  3. f.close()
  4. print(data)

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

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】
 
  1. # r+ 模式
  2. f = open('test.log','r+',encoding='utf-8')
  3. print(f.tell())#打印当前指针所在的位置,此时为0
  4. data = f.read()
  5. print(data)
  6. print(f.tell())#此时当前指针在文件最末尾
  7. f.close()
 
  1. # w+模式:先清空文件,再写入文件,写入文件后才可以读文件
  2. f = open('test.log','w+',encoding="utf-8")
  3. f.write('python')#写完后,指针到了最后
  4. f.seek(0)#移动指针到开头
  5. data = f.read()
  6. f.close()
  7. print(data)
 
  1. # a+模式:打开的同时,指针已经到最后,
  2. # 写时,追加,指针到最后
  3. f = open('test.log','a+',encoding="utf-8")
  4. print(f.tell())#读取当前指针位置,此时指针已经到最后
  5. f.write('c++')
  6. print(f.tell())
  7. #此时要读文件必须把指针移动到文件开头
  8. f.seek(0)
  9. data = f.read();
  10. print(data)
  11. f.close()

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

  • rb 或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

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

二:文件操作

3.x版本

三:管理上下文

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

 
  1. with open('log','r') as f:
  2. ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

 
  1. with open('log1') as obj1, open('log2') as obj2:
  2. pass

可使用此方法对一个文件进行读操作,同时把数据又写入到另一个打开的文件中!

read()、readline() 和 readlines()

每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

.readline() 和 .readlines() 非常相似。它们都在类似于以下的结构中使用:

 
  1. fh = open('c:\\autoexec.bat')
  2. for line in fh.readlines():
  3. print line

.readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。另一方面,.readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。

练习题:用户名与密码的验证

首先新建一个文件,这里为test.log文件,内容为两行如下:

 
  1. admin$123
  2. ginvip$123456

1:让用户选择1或2,1为登录,2为注册

2:如果用户选择1,用户输入用户名与密码,然后与test.log文件中的用户名与密码进行验证,验证成功输出“登录成功”,否则“登录失败”

3:如果用户选择2,让用户输入用户名与密码,并与test.log文件中的用户名验证,如果test.log中用户名已经存在,则输出“该用户名已经存在”,否则将用户输入的用户与密码以上面test.log文件中的形式写入test.log文件中

 
  1. def check_user(user) :
  2. with open('test.log','r',encoding='utf-8') as f :
  3. for line in f :
  4. user_list = line.strip()
  5. user_list = user_list.split('$')
  6. if user == user_list[0] :
  7. return True
  8. return False
  9. def register(user,pwd) :
  10. with open('test.log','a',encoding='utf-8') as f :
  11. user_info = '\n' + user + '$' + pwd
  12. if f.write(user_info) :
  13. return True
  14. return False
  15. def login(user,pwd) :
  16. with open('test.log','r',encoding='utf-8') as f :
  17. for line in f:
  18. user_list = line.strip()
  19. user_list = user_list.split('$')
  20. if user == user_list[0] and pwd == user_list[1]:
  21. return True
  22. return False
  23. def main() :
  24. print('welcome to my website')
  25. choice = input('1:login 2:register')
  26. if choice == '':
  27. user = input('input username :')
  28. pwd = input('input password : ')
  29. if check_user(user) :
  30. print('the username is exist')
  31. else:
  32. if register(user,pwd) :
  33. print('register success')
  34. else:
  35. print('register failed')
  36. elif choice == '':
  37. user = input('input username :')
  38. pwd = input('input password : ')
  39. if login(user,pwd) :
  40. print('login success')
  41. else:
  42. print('login failed')
  43. main()

冒泡排序


冒泡排序的原理:

 
  1. def Bubble_sort(args) :
  2. for i in range(len(args)-1) :
  3. for j in range(len(args) -1):
  4. if args[j] > args[j+1]:
  5. temp = args[j]
  6. args[j] = args[j+1]
  7. args[j+1] = temp
  8. return args
  9. li = [33,2,10,1,9,3,8]
  10. print(Bubble_sort(li))

练习题

1、简述普通参数、指定参数、默认参数、动态参数的区别

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

 
  1. digit = 0
  2. case = 0
  3. space = 0
  4. other = 0
  5. def func2(s) :
  6. global digit,case,space,other
  7. if not isinstance(s,basestring) :
  8. print('the data type wrong!')
  9. return False
  10. for i in s :
  11. if i.isdigit() :
  12. digit += 1
  13. elif i.isalpha() :
  14. case += 1
  15. elif i.isspace() :
  16. space += 1
  17. else:
  18. other += 1
  19. s = 'I love python , is num 1 , o_k'
  20. a = [1,2,3]
  21. func2(s)
  22. print(digit)
  23. print(case)
  24. print(space)
  25. print(other)
  26. ########################################
  27. 1
  28. 18
  29. 8
  30. 3
  31. 问题:判断是不是字符串后直接退出函数,而不执行下面的代码?

第2题答案

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

 
  1. def func3(v) :
  2. if len(v) > 5 :
  3. return True
  4. else:
  5. return False
  6. a = 'I love python , is num 1 , o_k'
  7. l = [1,2,3]
  8. t = (5,7,9,10,45,10)
  9. print(func3(t))

第三题答案

4、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

5、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

 
  1. def func5(lis) :
  2. if len(lis) > 2 :
  3. return lis[0:2]
  4. else :
  5. return False
  6. li = [1,2,3]
  7. print(func5(li))
  8. ##########################################
  9. [1, 2]

第五题答案

6、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

 
  1. def func6(lis) :
  2. new_lis = []
  3. for k in range(len(lis)) :
  4. if k % 2 == 1 :
  5. new_lis.append(lis[k])
  6. return new_lis
  7. li = [1,2,3,8,10,44,77]
  8. tu = ('poe','andy','jet','bruce','jacky')
  9. print(func6(tu))
  10. ##########################################
  11. ['andy', 'bruce']

第六题答案

7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

 
  1. dic = {"k1": "v1v1", "k2": [,,,]}
  2. PS:字典中的value只能是字符串或列表
 
  1. def func7(d) :
  2. v = d.values()
  3. li = []
  4. for i in v :
  5. if len(i) > 2:
  6. li.append(i[0:2])
  7. return li
  8. print(func7(dic))
  9. ##########################################
  10. [[11, 22], 'v1']

第七题答案

8、写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者

 
  1. def fabonacci(n) :
  2. if n == 0 :
  3. return 0
  4. elif n == 1:
  5. return 1
  6. else:
  7. return fabonacci(n-1) + fabonacci(n-2)
  8. print(fabonacci(10))

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值