python常用函数记录

map内置函数:

"""
map(function,iterable...)函数是python中的内置函数
参数
function: 函数名
iterable:一个或者多个序列(可迭代对象)
"""
import math
# 常见用法
# int转String
result = eval(input())
print(",".join(list(map(str, range(result)))))
# 输出:0,1,2,3,4,5,6,7,8,9

# 给列表中的每个元素平方
def square(x):
    return x * x
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result2 = map(square, a)
print(list(result2))
# 输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 使用lambda 表达式
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(map(lambda x : x*x, a)))

# 给列表中每个元素开方
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result3 = map(math.sqrt, a)
print(list(result3))
# 输出:[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]

# 接收多个可迭代对象,计算多种值
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 4, 5, 6, 7, 10, 9]
print(list(map(lambda x, y: (x+y, x*y), a, b)))
# 输出:[(0, 0), (2, 1), (4, 4), (6, 9), (8, 16), (10, 25), (12, 36), (14, 49), (18, 80), (18, 81)]

python中f(f-string)的用法:格式化字符串常量

"""
python中用于格式化输出f的用法
f是format的缩写
format函数常见的用法是str.format(),是通过{}和:来代替以前的%。
"""
# format用法:
"{} {}".format("hello", "world")
# 输出:'hello world'
"{0} {1}".format("hello", "world") # 设置指定位置
# 输出:'hello world'
"{1} {0} {1}".format("hello", "world") # 设置指定位置
# 输出:'world hello world'
# 注:如字符串中需要展示大括号,则再套一个大括号包裹起来转义。

# format参数式用法:
"hello:{p}".format(p="world")
# 输出:hello:world

# format数字格式化用法:
"{:.2f}".format(12345678.90) # 保留两位小数
# 输出:12345678.90

# 指定日期格式
from datetime import datetime
dt = datetime.now()
a = dt.strftime("%Y-%m-%d %H:%M:%S")
print(a)

# f-string用法:
f"{12345678.90:.2f}" # 保留两位小数  12345678.90

for i, j in enumerate(a):
    print(f"{i}-{j}")

在这里插入图片描述

round函数

"""
round函数是python内置函数,用于数字四舍五入的处理
round(number,digits)
参数:
    digits>0,四舍五入到指定的小数位
    digits=0, 四舍五入到最接近的整数
    digits<0 ,在小数点左侧进行四舍五入
    不写digits作用等同于传0
"""
round(3.14, 2) # 输出:3.14,只有两位小数,digits大于小数位,不会补0
round(3.14, 0) # 输出:3
round(3.54, 2) # 输出:4
round(3.14, -1) # 输出:0.0
round(5.14, -1) # 输出:10.0
round(3.14) # 输出:3

eval函数

"""
作用:
    eval()函数用于执行一个字符串表达式,并且返回该表达式的值。
    可以做string与list,tuple,dict、int之间的类型转换,还可以做计算器使用!
    慎用eval做用户输入校验,有安全隐患
        如:eval("__import__('os').system('dir')")
相近函数:exec
语法格式:eval(expression, globals=None, locals=None)
参数:
    expression:字符串表达式, 必须是字符串
    globals:可选参数,变量作用域,全局命名空间,必须是字典格式,定义了该参数后,eval函数的作用域就会被限定在globals中
    locals:可选参数,变量作用域,局部命名空间,可以是任意映射对象,定义了该参数后,当参数冲突时,会执行locals处的参数。
        映射对象:字典(dict)、集合(set)、枚举(Enum)、抽象映射(collections.abc.Mapping)、
                映射代理(collections.MappingProxyType)和缺省字典(collections.defaultdict)。
"""
# 字符串转int
print(type(eval('1')))

# 字符串转list
print(eval('[1, 2, 3, 4, 5]'))

# 字符串转tuple
print(eval('(1, 2, 3, 4)'))

# 字符串转dict
print(eval("{'name': 'Jerry'}"))

# 危险用法,执行系统命令
print(eval("__import__('os').system('dir')")) # 可以使用ast.literal_eval代替eval

# globals参数案例
a = 10
g = {'a': 5}
print(eval('a + 1', g)) # 指定了globals,那么expression部分的作用域就是globals指定的范围  输出:6

# locals参数案例
a = 10
b = 20
c = 30
g = {'a': 6, 'b': 8}
l = {'b': 100, 'c': 10}
print(eval('a + b + c', g, l))
# 指定了globals和locals,所以a=10,b=20,c=30不会被应用,ac取了globals和locals中的ac,b它们中都有,所以取locals中

enumerate函数

"""
enumerate()是python的内置函数,将一个可遍历iterable数据对象(如list列表、
tuple元组或str字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中。
语法:enumerate(sequence, [start=0])
参数:
    sequence:iterable可迭代对象
    start:下标索引起始位置
返回值:enumerate(枚举) 对象
"""

# 迭代列表访问下标索引,for循环方式
l=[22, 36, 54, 41, 19, 62, 14, 92, 17, 67]
for i in range(len(l)):
    print(i, ":", l[i])

# enumerate方式
for i, item in enumerate(l):
    print(i, ":", item)

# 改变索引起始位置,从1开始
for i, item in enumerate(l, 1):
    print(i, ":", item)

zip函数

zip函数是python的内置函数
作用:以可迭代对象作为参数,将对象中的元素打包成一个个元组,
回这些元组组成的对象。如果各个迭代器元素个数不同,则在最短的序列用完时就会停止
语法:zip(iterable, …)
参数:iterable(可迭代对象,如:字符串,元组,列表,字典等)
返回值:zip对象(多个元组组成的对象)(如果需要输出,需要手动转为其他对象输出)
如:list(zip(iterable, …))

# 传递一个参数
print(zip("hello"))  # 返回一个zip可迭代对象
print(tuple(zip("hello")))
print(list(zip("hello")))
print(tuple(zip([1, 2, 3, 4])))
print(list(zip({'name': 'xm', 'age': 20})))

# 传递多个参数
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['A', 'B', 'C', 'D', 'E']
print(list(zip(list1, list2)))

# 传递长度不等的参数  输出的元素数量等于最短迭代的长度
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['A', 'B', 'C', 'D']
print(list(zip(list1, list2)))

# 并行遍历多个字典
dict_one = {'name': 'David', 'age': 20}
dict_two = {'name': 'John', 'age': 23}
for (k1, v1), (k2, v2) in zip(dict_one.items(), dict_two.items()):
    print(k1, ':', v1)
    print(k2, ':', v2)

# 解压缩
a = [('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D'), ('e', 'E')]
l, u = zip(*a)
print(l)
print(u)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值