python知识点_初级(汇总)

转自 @寒小阳

1.9 函数

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。

你可以定义一个由自己想要功能的函数,以下是简单的规则:

  • 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

1.9.1 函数定义

def my_sum(a, b):
    "我是一个求和函数"
    return a+b+1
my_sum(4,5)

10

# 定义斐波那契数列
def fib(n):
    a, b =1, 1
    for i in range(n):
        print(a, end=" ")
        a,b = b,a+b
    print()

fib(10)

1 1 2 3 5 8 13 21 34 55

1.9.2 默认参数

# 函数默认参数
def printinfo(name, age = 35):
   print("姓名:", name)
   print("年龄:", age)
   return
 
#调用printinfo函数
printinfo(age=50, name="隔壁老王")
printinfo(name="隔壁老王")

姓名: 隔壁老王
年龄: 50
姓名: 隔壁老王
年龄: 35

1.9.3 变长参数函数

def printinfo(arg1, *vartuple):
   "打印任何传入的参数"
   print("输出:")
   print(arg1)
   print(vartuple)
   return
 
# 调用printinfo 函数
printinfo(10)
printinfo(70, 60, 50)

输出:
10
()
输出:
70
(60, 50)

1.9.4 匿名函数

# python 使用 lambda 来创建匿名函数。lambda [arg1,arg2,.....argn]:expression
sum = lambda arg1, arg2: arg1 + arg2;
 
# 调用sum函数
print("相加后的值为:", sum( 10, 20 ))
print("相加后的值为:", sum( 20, 30 ))

相加后的值为: 30
相加后的值为: 50

1.9.5 内置高阶函数

python中有很多非常实用的內建函数和高阶函数

1.9.5.1 filter

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

#判断是否为正数
def is_positive(x):
    return x > 0
result = filter(is_positive,[1,3,5,-1,-10,0])
list(result)

[1, 3, 5]

使用匿名函数lambda和filter函数筛选列表中大于0的数据

Ldata = [1, 2, 3, 4, 5, 6, -1, -2]
res1 = list(filter(lambda x: x > 0, Ldata))
print(res1)
输出结果如下:
[1, 2, 3, 4, 5, 6]

#挑选df中,每行全部大于0,的行
df0 = df[df.apply(lambda x: len(list(filter(lambda y: y > 0, x))) == len(x), axis=1)]
# 差分后,剔除全为正之后
df_1 = df[df.apply(lambda x: len(list(filter(lambda y: y > 0, x[:5]))) >= 4, axis=1)]

查找哪个月只有一个人过生日

A.groupby(A["生日"].apply(lambda x:x.month), as_index=False) # 到这里是按月分组

A.groupby(A["生日"].apply(lambda x:x.month), as_index=False).filter(lambda x: len(x)==1)

filter(function, iterable)

1、过滤出列表中的所有奇数:

def is_odd(n):
    return n % 2 == 1
 
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

2、过滤出列表中的所有偶数:

l = [x for x in range(10)]
print(list(filter(lambda x : x%2 == 0, l)))

3、过滤出1~100中平方根是整数的数:

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
 
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)

# [1, 3, 5, 7, 9]

4、删除1-20中素数

L = range(1, 21)

def isprimer(n):
    flag = 1
    for i in range(2, n):
        if n % i == 0:
            flag = 0
    if flag == 0:
        return n

print(list(filter(isprimer, L)))
# [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20]

5、去除空格和空值

def not_empty(s):
  return s and s.strip()

filter(not_empty, ['A', '', 'B', None, 'C', ' '])

6、高阶运用

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
        
def _not_divisible(n): 
    return lambda x : x%n>0
 
def primes():
    yield 2
    it = _odd_iter()
    ftr = filter(_not_divisible(2), it) #1
    while True:
        n = next(ftr )        #2
        yield n                
        ftr = filter(_not_divisible(n), ftr ) #3
        
for n in primes():
    if n < 20:
        print('now:',n)
    else:
        break
输出:
now: 2
now: 3
now: 5
now: 7
now: 11
now: 13
now: 17
now: 19
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值