python内建函数(不完全)

简介:


各位还是参考官方文档吧,我这些是自己感觉重要和常用的

abs ()
all (iterable) 如果迭代序列中所有的元素都为真,或者迭代序列为空的时候返回 True 。等价于:
def  all (iterable):
     for  element in  iterable:
         if  not  element:
             return  False
     return  True
all (iterable) 如果迭代序列中所有的元素都为真,返回 True 。等价于
def  any (iterable):
     for  element in  iterable:
         if  element:
             return  True
     return  False
complex ()创建复数:
>>> complex ( 1 , 2 )
( 1 + 2j )
>>> complex ( 1 )
( 1 + 0j )
delattr ( object , name)
For example, delattr (x, 'foobar' ) is  equivalent to del  x.foobar.
dict ()创建字典
dir ()
>>> import  struct
>>> dir ()   # show the names in the module namespace
[ '__builtins__' , '__doc__' , '__name__' , 'struct' ]
>>> dir (struct)   # show the names in the struct module
[ 'Struct' , '__builtins__' , '__doc__' , '__file__' , '__name__' ,
  '__package__' , '_clearcache' , 'calcsize' , 'error' , 'pack' , 'pack_into' ,
  'unpack' , 'unpack_from' ]
>>> class  Shape( object ):
         def  __dir__( self ):
             return  [ 'area' , 'perimeter' , 'location' ]
>>> s =  Shape()
>>> dir (s)
[ 'area' , 'perimeter' , 'location' ]
divmod (I,j)返回以商和余数组成的元祖:
>>> divmod ( 10 , 3 )
( 3 , 1 )
enumerate (sequence[, start = 0 ])
>>> seasons =  [ 'Spring' , 'Summer' , 'Fall' , 'Winter' ]
>>> list ( enumerate (seasons))
[( 0 , 'Spring' ), ( 1 , 'Summer' ), ( 2 , 'Fall' ), ( 3 , 'Winter' )]
>>> list ( enumerate (seasons, start = 1 ))
[( 1 , 'Spring' ), ( 2 , 'Summer' ), ( 3 , 'Fall' ), ( 4 , 'Winter' )]
其实也就等价于:
def  enumerate (sequence, start = 0 ):
     n =  start
     for  elem in  sequence:
         yield  n, elem
         n + =  1
eval (expression[, globals [, locals ]])
>>> x =  1
>>> print  eval ( 'x+1' )
2
filter (function, iterable) is  equivalent to [item for  item in  iterable if  function(item)] if  function is  not  None and  [item foritem in  iterable if  item] if  function is  None .
getattr ( object , name[, default])
  For example, getattr (x, 'foobar' ) is  equivalent to x.foobar.
hasattr ( object , name)
help ([ object ])¶
hex (x) 将整形x转化为 16 进制字符串,如果想要转化浮点型,可以使用 float . hex (x)
id ( object ) 对象的内存地址
input ([prompt]) Equivalent to eval ( raw_input (prompt)).
isinstance ( object , classinfo)
issubclass ( class , classinfo)
iter (o[, sentinel]) 迭代o,直到指和sentinel相等。例如:reads a file  until the readline() method returns an empty string:
with open ( 'mydata.txt' ) as fp:
     for  line in  iter (fp.readline, ''):
         process_line(line)
map (function, iterable, ...) Apply  function to every item of iterable and  return  a list  of the results.
max (iterable[, args...][, key])
min (iterable[, args...][, key])
next (iterator[, default])
oct (x)
Convert an integer number (of any  size) to an octal string. The result is  a valid Python expression.
open (name[, mode[, buffering]])
property ([fget[, fset[, fdel[, doc]]]])
class  C( object ):
     def  __init__( self ):
         self ._x =  None
 
     def  getx( self ):
         return  self ._x
     def  setx( self , value):
         self ._x =  value
     def  delx( self ):
         del  self ._x
     x =  property (getx, setx, delx, "I'm the 'x' property." )
创建只读属性:这个属性的值就不能修改了
class  Parrot( object ):
     def  __init__( self ):
         self ._voltage =  100000
 
     @property
     def  voltage( self ):
         """Get the current voltage."""
         return  self ._voltage
 
 
class  C( object ):
     def  __init__( self ):
         self ._x =  None
 
     @property
     def  x( self ):
         """I'm the 'x' property."""
         return  self ._x
 
     @x .setter
     def  x( self , value):
         self ._x =  value
 
     @x .deleter
     def  x( self ):
         del  self ._x
range ([start], stop[, step])
>>> range ( 10 )
[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> range ( 1 , 11 )
[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
>>> range ( 0 , 30 , 5 )
[ 0 , 5 , 10 , 15 , 20 , 25 ]
>>> range ( 0 , 10 , 3 )
[ 0 , 3 , 6 , 9 ]
>>> range ( 0 , - 10 , - 1 )
[ 0 , - 1 , - 2 , - 3 , - 4 , - 5 , - 6 , - 7 , - 8 , - 9 ]
>>> range ( 0 )
[]
>>> range ( 1 , 0 )
[]
reduce (function, iterable[, initializer])
Apply  function of two arguments cumulatively to the items of iterable, from  left to right, so as to reduce  the iterable to a single value. For example, reduce ( lambda  x, y: x + y, [ 1 , 2 , 3 , 4 , 5 ]) calculates (((( 1 + 2 ) + 3 ) + 4 ) + 5 ). The left argument, x, is  the accumulated value and  the right argument, y, is  the update value from  the iterable. If the optional initializer is  present, it is  placed before the items of the iterable in  the calculation, and  serves as a default when the iterable is  empty. If initializer is  not  given and  iterable contains only one item, the first item is  returned.
round (x[, n])
>>> round ( 1.12313 , 2 )
1.12
slice ([start], stop[, step])
sorted (iterable[, cmp [, key[, reverse]]])
staticmethod (function)
Return a static method for  function.
class  C:
     @staticmethod
     def  f(arg1, arg2, ...): ...
sum (iterable[, start])
tuple ([iterable])
>>> tuple ( "ada" )
( 'a' , 'd' , 'a' )
zip ([iterable, ...])
zip () in  conjunction with the *  operator can be used to unzip a list :
>>> x =  [ 1 , 2 , 3 ]
>>> y =  [ 4 , 5 , 6 ]
>>> zipped =  zip (x, y)
>>> zipped
[( 1 , 4 ), ( 2 , 5 ), ( 3 , 6 )]
>>> x2, y2 =  zip ( * zipped)
>>> x = =  list (x2) and  y = =  list (y2)
True
 
>>> float .fromhex( '0x3.a7p10' )
3740.0
 
>>> lists =  [[]] *  3
>>> lists
[[], [], []]
>>> lists[ 0 ].append( 3 )
>>> lists
[[ 3 ], [ 3 ], [ 3 ]]
 
>>> lists =  [[] for  i in  range ( 3 )]
>>> lists[ 0 ].append( 3 )
>>> lists[ 1 ].append( 5 )
>>> lists[ 2 ].append( 7 )
>>> lists
[[ 3 ], [ 5 ], [ 7 ]]
 
>>> "The sum of 1 + 2 is {0}" . format ( 1 + 2 )
'The sum of 1 + 2 is 3'
 
>>> "they're bill's friends from the UK" .title()
"They'Re Bill'S Friends From The Uk"
 
>>> print  '%(language)s has %(number)03d quote types.'  %  \
...       { "language" : "Python" , "number" : 2 }
Python has 002  quote types.
 
>>> dishes =  { 'eggs' : 2 , 'sausage' : 1 , 'bacon' : 1 , 'spam' : 500 }
>>> keys =  dishes.viewkeys()
>>> values =  dishes.viewvalues()
 
>>> # iteration
>>> n =  0
>>> for  val in  values:
...     n + =  val
>>> print (n)
504
 
>>> # keys and values are iterated over in the same order
>>> list (keys)
[ 'eggs' , 'bacon' , 'sausage' , 'spam' ]
>>> list (values)
[ 2 , 1 , 1 , 500 ]
 
>>> # view objects are dynamic and reflect dict changes
>>> del  dishes[ 'eggs' ]
>>> del  dishes[ 'sausage' ]
>>> list (keys)
[ 'spam' , 'bacon' ]
 
>>> # set operations
>>> keys & { 'eggs' , 'bacon' , 'salad' }
{ 'bacon' }
 
>>> v =  memoryview( 'abcefg' )
>>> v[ 1 ]
'b'
>>> v[ - 1 ]
'g'
>>> v[ 1 : 4 ]
<memory at 0x77ab28 >
>>> v[ 1 : 4 ].tobytes()
'bce'
 
>>> data =  bytearray( 'abcefg' )
>>> v =  memoryview(data)
>>> v.readonly
False
>>> v[ 0 ] =  'z'
>>> data
bytearray(b 'zbcefg' )
>>> v[ 1 : 4 ] =  '123'
>>> data
bytearray(b 'z123fg' )
>>> v[ 2 ] =  'spam'
Traceback (most recent call last):
   File  "<stdin>" , line 1 , in  <module>
ValueError: cannot modify size of memoryview object
 
>>> m =  memoryview( "abc" )
>>> m.tobytes()
'abc'
 
>>> memoryview( "abc" ).tolist()
[ 97 , 98 , 99 ]

  


==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2011/11/25/2263726.html,如需转载请自行联系原作者
相关文章
|
5月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
376 1
|
5月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
852 1
|
5月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
324 0
|
6月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
335 101
|
6月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
280 99
|
6月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
363 98
|
6月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
7月前
|
Python
Python 函数定义
Python 函数定义
708 155
|
8月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
694 0
|
6月前
|
算法 安全 数据安全/隐私保护
Python随机数函数全解析:5个核心工具的实战指南
Python的random模块不仅包含基础的随机数生成函数,还提供了如randint()、choice()、shuffle()和sample()等实用工具,适用于游戏开发、密码学、统计模拟等多个领域。本文深入解析这些函数的用法、底层原理及最佳实践,帮助开发者高效利用随机数,提升代码质量与安全性。
1075 0

推荐镜像

更多