设为首页 收藏本站
查看: 711|回复: 0

[经验分享] python内建函数(不完全)

[复制链接]

尚未签到

发表于 2015-4-24 05:27:20 | 显示全部楼层 |阅读模式
  各位还是参考官方文档吧,我这些是自己感觉重要和常用的



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]

>>> 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 "", line 1, in
ValueError: cannot modify size of memoryview object
>>> m = memoryview("abc")
>>> m.tobytes()
'abc'
>>> memoryview("abc").tolist()
[97, 98, 99]

  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-60011-1-1.html 上篇帖子: Python与中文 下篇帖子: mac 安装 mysql-python 折腾记
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表