isunny

前言

在Python官方文档的标准库章节中,第一节是简介,第二节就是Built_in Functions,可见内建函数是Python标准库的重要组成部分,而有很多内建函数我们平时却很少用到或根本就不知道原来还有这么好用的函数居然直接就可以拿来用。

Built_in Funtions

接下来为大家介绍一些我认为被大家忽略掉的内建函数。

all

如果列表或迭代器中所有值都为真或为空返回True,相当于

def all(iterable):
    for element in iterable:
       if not element:      
            return False    return True

any

如果迭代器中至少有一个值为真返回True,若迭代器为空返回False,相当于

def any(iterable):
    for element in iterable:
       if element:      
           return True    return False

dir

没有参数时返回当前作用域的所有名称,有参数时返回该参数的所有属性

>>> dir(int)
[\'__abs__\', \'__add__\', \'__and__\', \'__bool__\', \'__ceil__\', \'__class__\', \'__delattr__\', \'__dir__\', \'__divmod__\', \'__doc__\', \'__eq__\', \'__float__\', \'__floor__\', \'__floordiv__\', \'__format__\', \'__ge__\', \'__getattribute__\', \'__getnewargs__\', \'__gt__\', \'__hash__\', \'__index__\', \'__init__\', \'__int__\', \'__invert__\', \'__le__\', \'__lshift__\', \'__lt__\', \'__mod__\', \'__mul__\', \'__ne__\', \'__neg__\', \'__new__\', \'__or__\', \'__pos__\', \'__pow__\', \'__radd__\', \'__rand__\', \'__rdivmod__\', \'__reduce__\', \'__reduce_ex__\', \'__repr__\', \'__rfloordiv__\', \'__rlshift__\', \'__rmod__\', \'__rmul__\', \'__ror__\', \'__round__\', \'__rpow__\', \'__rrshift__\', \'__rshift__\', \'__rsub__\', \'__rtruediv__\', \'__rxor__\', \'__setattr__\', \'__sizeof__\', \'__str__\', \'__sub__\', \'__subclasshook__\', \'__truediv__\', \'__trunc__\', \'__xor__\', \'bit_length\', \'conjugate\', \'denominator\', \'from_bytes\', \'imag\', \'numerator\', \'real\', \'to_bytes\']

divmod

同时返回整数除法的商和余数

>>> divmod(11,3)       
(3, 2)                 

enumerate

同时返回迭代器元素的索引和值,索引的初始值可以设置,在需要知道元素位置的for循环中很好用

>>> for index, value in enumerate(\'ABCDEFG\'):
...    print(index, value) ...
0 A
1 B
2 C
3 D
4 E
5 F
6 G

id

对于CPython来说就是对象的内存位置

>>> x, y = 1, 2
>>> id(x), id(y) (1666253264, 1666253296)

isinstance

判断第一个参数是否是第二个参数的实例,以后不要用type(1) == int

>>> isinstance(\'A\',str)
True

结语

希望大家在日后的开发中合理的使用好这些内建函数。

 

原文地址:https://segmentfault.com/a/1190000008604077

分类:

技术点:

相关文章:

  • 2022-01-19
  • 2022-01-07
  • 2021-09-25
猜你喜欢
  • 2022-01-13
  • 2022-12-23
  • 2021-12-18
  • 2021-11-15
  • 2021-10-17
  • 2021-08-19
相关资源
相似解决方案