python内置函数(二)

39 篇文章 0 订阅
32 篇文章 1 订阅

内置函数

函数用途
len(s)返回对象的长度(元素个数)
max(iterable, *[, key, default])返回可迭代对象中最大的元素
min(iterable, *[, key, default])返回可迭代对象中最小的元素
chr(i)返回unicode码对应的字符
ord(c)返回字符对应的unicode码
open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)打开 file 并返回对应的 file object
help([object])启动内置帮组系统
dir([object])返回当前作用域中的名称列表;若参数是对象,则返回对象有效的属性列表
iter(object[, sentinel])返回一个 iterator 对象
next(iterator[, default])通过调用 iterator 的 __next__() 方法获取下一个元素
all(iterable)可迭代对象中的所有元素均为真或者可迭代对象为空时,返回True,否则返回False
any(iterable)可迭代对象中的任意一元素均为真,返回True,若可迭代对象为空时,返回False
zip(*iterables)创建一个聚合了来自每个可迭代对象中的元素的迭代器
reversed(seq)返回一个反向的 iterator,seq 必须是一个具有 __reversed__() 方法的对象或者是支持该序列协议(具有从 0 开始的整数类型参数的 len() 方法和 __getitem__() 方法)
sorted(iterable, *, key=None, reverse=False)根据 iterable 中的项返回一个新的已排序列表

函数使用实例

len、max、min

max/min:返回其中最大或者最小的值,输入一个值时则取此值中的最大或者最小,输入多个值时,则取这几个值中最大或者最小

>>> len('abc d')
5
>>> max("abcA")
'c'
>>> min("abcA")
'A'
>>> max("abc","cba")
'cba'
>>> min([1,2,3],[1,2,2])
[1, 2, 2]

min中key值使用,获取字典中value值最小的一个

dic = {"A": 41, "B": 42, "C":1}
min(dic.keys(),key=dic.get) #输出 C

chr,ord

>>> chr(65)
'A'
>>> ord('A')
65

open

with open('1.txt','w',encoding='utf8') as f:
    f.write('输出内容')

打开方式的参数有

字符含义
‘r’读取(默认)
‘w’写入,并先截断文件
‘x’排它性创建,如果文件已存在则失败
‘a’写入,如果文件存在则在末尾追加
‘b’二进制模式
‘t’文本模式(默认)
‘+’打开用于更新(读取与写入)

help

如果没有实参,解释器控制台里会启动交互式帮助系统。如果实参是一个字符串,则在模块、函数、类、方法、关键字或文档主题中搜索该字符串,并在控制台上打印帮助信息

def TestHelpFunc():
    '''这是函数的使用方法'''
    pass
class TestHelp():
    '''这是对象方法'''
    pass
help()
print("*"*40)
help(TestHelpFunc)
print("*"*40)
help(TestHelp)

输出结果:第一部分时help()输出的结果,以下分别是对象函数、方法的帮组信息的输出结果

Welcome to Python 3.8's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.8/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> >? 
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
****************************************
Help on function TestHelpFunc in module __main__:
TestHelpFunc()
    这是函数的使用方法
****************************************
Help on class TestHelp in module __main__:
class TestHelp(builtins.object)
 |  这是对象方法
 |  
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

dir

如果没有实参,则返回当前本地作用域中的名称列表。如果有实参,它会尝试返回该对象的有效属性列表

a=b=1
x=dir()   
class TestDir():
    x=1
    def testfun(self):
        pass
y=dir(TestDir)

返回x,y的分别是

x:['Iterable', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b']
y:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'testfun', 'x']

iter、next

  • iter把可迭代对象转为迭代器
  • next调用迭代器的__next__() 方法获取下一个元素
>>> from collections.abc import Iterator
>>> isinstance([1,2],Iterator)
False
>>> isinstance(iter([1,2]),Iterator)
True
i=iter([1,2])
next(c)  #返回1
next(c)  #返回2
next(c)  #访问到最后会报错;StopIteration

all,any

  • all:可迭代对象的元素都为真或者是空的迭代对象,返回True
  • any:可迭代对象任意一个元素为真时,返回True
>>> all([1,2,3,''])
False
>>> all([])
True
>>> any([1,2,3,''])
True
>>> any([])
False

zip

x=('a','b','c')
y=[1,2,3]
z=zip(x,y)
#dic=dict(z)   #代码1
#l=list(z)    #代码2
x2, y2 = zip(*z)  #代码3
  • 输出结果
    dic :{'a': 1, 'b': 2, 'c': 3}
    l:[('a', 1), ('b', 2), ('c', 3)]
    x2:('a', 'b', 'c')
    y2:(1, 2, 3)
    
  • 注意代码1,2,3是不能同时执行成功的,因为zip返回的值是迭代器,迭代器只能访问一次

reversed

返回一个反向的迭代器

>>> list(reversed("abc"))
['c', 'b', 'a']
>>> list(reversed([1,2,3]))
[3, 2, 1]

sorted

  • 根据 iterable 中的项返回一个新的已排序列表
  • reverse参数为True时表示按反向顺序比较进行排序
  • key参数:带有单个参数的函数
>>> sorted([2,1,2,3])
[1, 2, 2, 3]
>>> sorted([2,1,2,3],reverse=True)
[3, 2, 2, 1]
L=[('b',2,'f'),('a',1,'m'),('c',3,'m'),('d',4,'f')]
s=sorted(L,key=lambda x:x[2])   #返回[('b', 2, 'f'), ('d', 4, 'f'), ('a', 1, 'm'), ('c', 3, 'm')]
dic={'a':1,'b':3,'c':2}
  • 字典分别根据key或者value排序
#只排序key值,返回列表
sort=sorted(dic)  #返回['a', 'b', 'c']   
#根据key值排序,返回字典
sort1=sorted(dic.items())   #返回[('a', 1), ('b', 3), ('c', 2)]
#优先根据value排序,其次根据key排序
sort2=sorted(dic.items(),key=lambda x:(x[1],x[0]))   #返回[('a', 1), ('c', 2), ('b', 3)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值