python数据分析课程笔记 | 第一章 Python基本运用(下)

本文介绍了Python的基础函数应用,包括max/min、四舍五入、字符串格式化、枚举等。深入探讨了lambda、map、reduce和filter等高级函数,以及字符串处理的技巧,如转换、裁剪、判断和计数。适合进一步提升Python编程技能。

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

1.4 函数介绍

# 常用内置函数
a = [1, 2, 3, 4, 5]
element_max = max(a)
element_min = min(a)

element = round(4.2424451, 2)  # 四舍五入

b = 'hello,world'
isinstance(b, str)
len(b)

c = ['one', 'two', 'three']
for i, j in enumerate(c):  # 枚举
    print(i, j)

list1 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4]
e = list(zip(list1, list2))

# 第三方库
import math
math.floor(4.7)  # 向下取整
math.ceil(4.7)  # 向上取整

import numpy as np
np.min([1, 4, 6, 7])
np.argmin([1, 4, 6, 7])

# 自定义函数
def exponent(a, b):
    x = a ** b
    return x

def ssn(n, beg=1):
    s = 0
    for i in range(beg, n+1):
        s += i
    return s

1.5 字符串处理

具体可查看:https://www.runoob.com/python/python-strings.html

# 字符串格式化
print('我今年%s岁,目前薪水%s以上' % (30, '2万'))
print('我今年{:.2f}岁,目前薪水{}以上'.format(30, '2万'))
# 大小写转换
filed = 'This is me'
filed.upper()
filed.capitalize()
# 去空格
tele = ' This is me '
tele.strip()
tele.rstrip()
tele.lstrip()
# 判断是不是全是数字
tele.isdigit()
# 判断是不是以参数开头
tele.startswith(' This')
# 判断是不是由数字和字母构成的
tele.isalnum()
# 统计次数
tele.count('i')

1.6 高级函数

(1)lambda函数(匿名函数)

匿名函数:

  • 不需要使用def来定义,使用lambda来定义函数
  • 没有具体名称
  • 语法结构:lmbda par1,par2,···parn:expression
g = lambda x: x**2
a = g(2)

f1 = lambda x: 'A' if x == 1 else 'B'
b = f1(100)  # B
c = f1(1)  # A

total = lambda x, y, z: x+2*y+3*z
d = total(1, 2, 3)

(2)map函数

在这里插入图片描述
在这里插入图片描述

def f(x):
    return x**2

items = [1, 2, 3, 4, 5, 6]
a = list(map(f, items))
b = list(map(lambda x: x**2, items))

(3)reduce函数

在这里插入图片描述
在这里插入图片描述

from functools import reduce

def f(x,y):
    return x+y

items = range(1, 101, 1)
result = reduce(f, items)

map和reduce强大在于联系在一起用,如:reduce(func2,map(func1,iter))

(4)filter函数

  • 语法结构:filter(function, sequnce)
  • 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的序列
  • 将function依次作用于sequnce的每个item,即function(item),将返回值为True的item组成一个list、string、tuple(取决于sequnce的类型)
a = list(filter(lambda x: x % 2 == 0, range(21)))

items = [1, 2, 3, 4, '3234', 'ine', '-34.56', 45.8, -7]
b = list(filter(lambda x: 1 if isinstance(x, int) else 0, items))

def int_num(x):
    if isinstance(x, int):
        return True
    else:
        return False

c = list(filter(int_num, items))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值