Python内置函数
1
阅本文需要2分钟
pow() 方法返回 xy(x的y次方) 的值。
以下是 math 模块 pow() 方法的语法:
import math math.pow( x )
内置的 pow() 方法:
pow(x, y[, z])
函数是计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于:pow(x,y) %z
注意:pow() 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块则会把参数转换为 float。
返回 xy(x的y次方) 的值。
以下展示了使用 pow() 方法的实例:
import math # This will import math module
print( "math.pow(100, 2) : ", math.pow(100, 2))
print( "math.pow(100, -2) : ", math.pow(100, -2))
print("math.pow(2, 4) : ", math.pow(2, 4))
print("math.pow(3, 0) : ", math.pow(3, 0))
以上实例运行后输出结果为:
math.pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0
Python len() 方法返回字符串长度。
len()方法语法:
len( s )
返回对象长度。
以下实例展示了len()的使用方法:
>>>str = "w3cschool"
>>> len(str) # 字符串长度
9
>>> l = [1,2,3,4,5]
>>> len(l) # 列表元素个数
5
range() 函数可创建一个整数列表,一般用在 for 循环中。
range(start, stop[, step])
参数说明:
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
以下是 range 在 for 中的使用,循环出 w3cschool 的每个字母:
>>>x = 'school'
>>> for i in range(len(x)) :
... print(x[i])
...
s
c
h
o
o
l
>>>
Python type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
isinstance() 与 type() 区别:
如果要判断两个类型是否相同推荐使用 isinstance()。
以下是 type() 方法的语法:
type(object)
type(name, bases, dict)
一个参数返回对象类型, 三个参数,返回新的类型对象。
以下展示了使用 type 函数的实例:
# 一个参数实例
>>> type(1)
<type 'int'>
>>> type('school')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1
>>> type( x ) == int # 判断类型是否相等
True
# 三个参数
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1)) # 产生一个新的类型 X
>>> X
<class '__main__.X'>
type() 与 isinstance()区别:
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
Python map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
map() 函数语法:
map(function, iterable, ...)
Python 2.x 返回列表。
Python 3.x 返回迭代器。
以下实例展示了 map() 的使用方法:
>>>def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
Python help() 函数用于查看函数或模块用途的详细说明。
help 语法:
help([object])
参数说明:
返回对象帮助信息。
以下实例展示了 help 的使用方法:
>>>help('sys') # 查看 sys 模块的帮助
……显示帮助信息……
>>>help('str') # 查看 str 数据类型的帮助
……显示帮助信息……
>>>a = [1,2,3]
>>>help(a) # 查看列表 list 帮助信息
……显示帮助信息……
>>>help(a.append) # 显示list的append方法的帮助
……显示帮助信息……
END