Python中的多个内置函数举例

Python内置函数:

官方帮助文档:

https://docs.python.org/2.7/

返回数字的绝对值.

def fun(x):

if x < 0:

return -x

return x

print fun(10)
常用函数:

abs()

>>> abs(-100)

100
取列表最大值和最小值

max()

>>> max(‘1235‘,123)

‘1235‘
min()

>>> min(‘asdfq3w45‘)

‘3‘
len()

>>> len(‘abcdf‘)

5

>>> len([1,3,4,5])

4

>>> len((1,3,4,5))

4

>>> len({1:3,2:5})

2
divmod()

>>> help(divmod)

Help on built-in function divmod in module __builtin__:

divmod(...)

divmod(x, y) -> (quotient, remainder)

Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.

 >>> divmod(5,2)

(2, 1)
pow()

pow(...)

pow(x, y[, z]) -> number

With two arguments, equivalent to x**y.  With three arguments,

equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

>>> pow(2,3)

8

>>> pow(2,3,3)

2
round()

round(...)

round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).

This always returns a floating point number.  Precision may be negative.

>>> round(12.2)

12.0

>>> round(12.23)

12.0

>>> round(12.233,2)

12.23
callable()

是否是可调用对象

>>> a = 123

>>> callable(a)

False

>>> def a():

...     pass

...

>>> callable(a)

True

>>> class A(object):

...     pass

...

>>> callable(A)

True
type()

判断类型

>>> type(a)

<type ‘function‘>
isinstance()

判断类型,

>>> l =[1,2,3]

>>> isinstance(l,list)

True

>>> isinstance(l,str)

False

>>> isinstance(l,(list,str))

True

判断是不是一个类

>>> A

<class ‘A‘>

>>> a = A()

>>> a

<A object at 0x0379BE70>

>>> isinstance(a,A)

True
cmp()

>>> cmp(1,2)

-1

>>> cmp(1,0)

1

>>> cmp(1,1)

0

>>> cmp(‘a‘,‘ab‘)

-1

>>> cmp(‘a‘,‘a‘)

0

>>> cmp(‘helloa‘,‘hello‘)

1
range()

>>> a = range(10)

>>> a
xrange()

效率更高,不用时候不在内存中产生值

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> b = xrange(10)

>>> b

xrange(10)

>>> for i in b:print i

...

0

1

2

3

4

5

6

7

8

9
int()

>>> int(123.33)

123
long()

>>> long(200)

200L
float()

>>> float(‘123‘)

123.0

>>> float(‘123.0022‘)

123.0022

>>> float(123.0034)

123.0034

>>> float(123)

123.0
complex()

转换成复数

>>> complex(123)

(123+0j)

>>> complex(3.1415926)

(3.1415926+0j)
str()

>>> str(‘123‘)

‘123‘
list()

>>> list(‘123‘)

[‘1‘, ‘2‘, ‘3‘]
tuple()

>>> tuple(‘123‘)

(‘1‘, ‘2‘, ‘3‘)
hex()

变为16进制

>>> hex(10)

‘0xa‘

>>> hex(10L)

‘0xaL‘

>>> int(0xaL)

10
eval()

把字符串当成有效表达式求值。

>>> eval(‘0xaL‘)

10L

>>> eval("[1,23,‘a‘]")

[1, 23, ‘a‘]
oct()

10进制转成8进制

>>> oct(10)

‘012‘

>>> oct(8)

‘010‘
chr()

查ASSIC码对应值:

>>> chr(97)

‘a‘

>>> chr(65)

‘A‘
ord()

>>> ord(‘A‘)

65
字符串处理的函数:

str.capitalize()

首字母变大写:

capitalize(...)

S.capitalize() -> string

Return a copy of the string S with only its first character

capitalized.

>>> s

‘hello‘

>>> s.capitalize()

‘Hello‘
str.replace()

replace(...)

S.replace(old, new[, count]) -> string

Return a copy of string S with all occurrences of substring

old replaced by new.  If the optional argument count is

given, only the first count occurrences are replaced.

>>> s = ‘hello,h‘

>>> s.replace(‘h‘,‘H‘)

‘Hello,H‘
split()

split(...)

S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the

delimiter string.  If maxsplit is given, at most maxsplit

splits are done. If sep is not specified or is None, any

whitespace string is a separator and empty strings are removed

from the result.

>>> s = ‘hello a\tb\nc‘

>>> s

‘hello a\tb\nc‘

>>> s.split()

[‘hello‘, ‘a‘, ‘b‘, ‘c‘]

>> s

‘hello a\tb\nc‘

>>> s.split(‘ ‘)

[‘hello‘, ‘a\tb\nc‘]

>>> s.split(‘\t‘)

[‘hello a‘, ‘b\nc‘]

>>> ip = ‘192.168.1.1‘

>>> ip.split(‘.‘)

[‘192‘, ‘168‘, ‘1‘, ‘1‘]

>>> ip.split(‘.‘,1)

[‘192‘, ‘168.1.1‘]

>>> ip.split(‘.‘,2)

[‘192‘, ‘168‘, ‘1.1‘]
join()

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> ‘‘.join(str(i) for i in range(10))

‘0123456789‘

>>> int(‘‘.join(str(i) for i in range(10)))

123456789
string:

import string

string.lower

>>> string.lower(‘Kfdfa‘)

‘kfdfa‘

string.upper

>>> string.upper(‘Kfdfa‘)

‘KFDFA‘

string.capitalize()

>>> string.capitalize(‘adfafgh‘)

‘Adfafgh‘ 

string.replace()
string.replace(‘afkgha‘,‘a‘,‘A‘)

‘AfkghA‘
序列处理函数:

len()

max()

min()

filter()

filter(...)

filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If

function is None, return the items that are true.  If sequence is a tuple

or string, return the same type, else return a list.

>>> filter(None,range(10))

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> def f(x):

...     if x % 2 == 0:

...         return True

...

>>> filter(f,range(10))

[0, 2, 4, 6, 8]

>>> filter(lambda x: x%2==0,range(10))

[0, 2, 4, 6, 8]
zip()

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element

from each of the argument sequences.  The returned list is truncated

in length to the length of the shortest argument sequence.

>>> a1 = [1,3,4]

>>> a2 = [‘a‘,‘b‘,‘c‘]

>>> zip(a1,a2)

[(1, ‘a‘), (3, ‘b‘), (4, ‘c‘)]

>>> dict(zip(a1,a2))

{1: ‘a‘, 3: ‘b‘, 4: ‘c‘}

>>> dict(zip(a2,a1))

{‘a‘: 1, ‘c‘: 4, ‘b‘: 3}

>>> a3 = [‘x‘,‘y‘,‘z‘]

>>> zip(a1,a2,a3)

[(1, ‘a‘, ‘x‘), (3, ‘b‘, ‘y‘), (4, ‘c‘, ‘z‘)]

>>> zip(a1,a3)

[(1, ‘x‘), (3, ‘y‘), (4, ‘z‘)]

>>> a3 = [‘x‘,‘y‘]

>>> zip(a1,a3)

[(1, ‘x‘), (3, ‘y‘)]

>>> zip(a1,a2,a3)

[(1, ‘a‘, ‘x‘), (3, ‘b‘, ‘y‘)]
map()

map(...)

map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of

the argument sequence(s).  If more than one sequence is given, the

function is called with an argument list consisting of the corresponding

item of each sequence, substituting None for missing values when not all

sequences have the same length.  If the function is None, return a list of

the items of the sequence (or a list of tuples if more than one sequence).

参数有几个,函数里的参数也应该对应有几个

>>> map(None,a1,a2,a3)

[(1, ‘a‘, ‘x‘), (3, ‘b‘, ‘y‘), (4, ‘c‘, None)]

>>> def f(x):

...     return x**2

...

>>> map(f,a1)

[1, 9, 16]

>>> a1

[1, 3, 4]

>>> a1

[1, 3, 4]

>>> a2

[2, 5, 6]

>>> def f(x,y):

...     return x*y

...

>>> map(f,a1,a2)

[2, 15, 24]

>>> map(lambda x,y: x*y ,range(1,10),range(1,10))

[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce()

reduce(...)

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,

from left to right, so as to reduce the sequence to a single value.

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates

((((1+2)+3)+4)+5).  If initial is present, it is placed before the items

of the sequence in the calculation, and serves as a default when the

sequence is empty.

>>> def f(x,y):

...     return x + y

...

>>> reduce(f,range(1,101))

5050
列表表达式:

[i*2 for i in range(10)]

>>> [i*2 for i in range(10)]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> [i*2+10 for i in range(10)]

[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
[i*2+10 for i in range(10) if i%3 == 0]

>>> [i*2+10 for i in range(10) if i%3 == 0]

[10, 16, 22, 28]

原文地址:https://blog.51cto.com/fengyunshan911/2418748

时间: 2024-10-23 02:59:03

Python中的多个内置函数举例的相关文章

python中的作用域以及内置函数globals()-全局变量、locals()-局部变量

在python中,函数会创建一个自己的作用域,也称为为命名空间.这意味着在函数内部访问某个变量时,函数会优先在自己的命名空间中寻找. 通过内置函数globals()返回的是python解释器能知道的变量名称的字典(变量名:值): 而locals()函数返回的是函数内部本地作用域中的变量名称字典.由此可以看出,函数都是由自己独立的命名空间的. 查看全局变量和局部变量: #coding=utf-8 outerVar="this is a global variable"def test()

python基础12_匿名_内置函数

一个二分查找的示例: # 二分查找 示例 data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35, 36, 66] def binary_search(dataset, find_num): print(dataset) if len(dataset) > 1: mid = int(len(dataset) / 2) if dataset[mid] == find_num: # find it print

python&#39;s fourthday for me 内置函数

locals:  函数会以字典的类型返回当前位置的全部局部变量. globals:  函数会以字典的了类型返回全部的全局变量. a = 1 def func(): b = 2 print(locals()) print(globals()) func() 字符串类型的代码执行:eval, exec, complie eval: 执行字符串类型的代码,并返回最终结果. print(eval('2+2')) # 4 n = 4 print(eval('n+4')) # 8 eval('print(6

python补充最常见的内置函数

最常见的内置函数是: print("Hello World!") 数学运算 abs(-5)                         # 取绝对值,也就是5 round(2.6)                       # 四舍五入取整,也就是3.0 pow(2, 3)                        # 相当于2**3,如果是pow(2, 3, 5),相当于2**3 % 5 cmp(2.3, 3.2)                   # 比较两个数的大小

[python] 之all()和any()内置函数

在python 2.5版本以上开始引入,其基本使用方法如下: 一.all()内置函数 语法:all(iter) 说明: 1. iter为可迭代对象,比如列表,元组,字符串... 2. 若iter中的每一个元素(全部)都为布尔真(或布尔值意味着False的一些元素,比如'0','False',空字符' ' 等)时,返回True 3. 空的列表或元组,也返回True 二.any()内置函数 语法:any(iter) 说明: 1. iter为可迭代对象,比如列表,元组,字符串... 2. 若iter中

Python之lambda表达式和内置函数

lambda表达式其实就是简化的函数表达式. 它只用于处理简单逻辑, 它会自动return数据 通常定义一个函数,按照以下形式: def  func(arg):       return arg +1 result = func(100) print result 101 以上函数用lambda表达式可以这么写: func2 = lambda a: a+1 result = func2(100) print result 在lambda表达式中,func2 相当于函数表达式中的func,即函数的

Python基础(七)内置函数

今天来介绍一下Python解释器包含的一系列的内置函数,下面表格按字母顺序列出了内置函数: 下面就一一介绍一下内置函数的用法: 1.abs() 返回一个数值的绝对值,可以是整数或浮点数等. 1 2 3 4 5 6 print(abs(-18))          print(abs(0.15)) result: 18 0.15 2.all(iterable) 如果iterable的所有元素不为0.''.False或者iterable为空,all(iterable)返回True,否则返回False

python学习之路-4 内置函数和装饰器

本篇涉及内容 内置函数 装饰器 内置函数 callable()   判断对象是否可以被调用,返回一个布尔值 1 2 3 4 5 6 7 8 9 10 11 num = 10 print(callable(num))   # num不能够被调用,返回False    def f1():     print("name")    print(callable(f1))     # f1可以被调用,返回True    # 输出 False True ?chr()   将十进制整数转换为asc

Python自学之路——Python基础(四)内置函数

对上表一些比较重要常用的内置函数做一个整理 chr()与ord()     chr()是将ASCII中十进制编号转换成相应的字符,而ord()刚好相反 c = chr(49) o = ord('1') print(c) print(o) 输出结果: 1 49 知道了chr()的基本用法,可以利用它来生成一个字母验证码,因为验证码都是随机生成的,所以这里要涉及到random模块.在ASCII中,大写字母的十进制编号是从65到90. 小写字母是97到122 1 import random 2 li