Python内置函数(6)

Python内置函数(1)— abs()、all()、any()、ascii()、bin()、bool()、breakpoint()、bytearray()、bytes()、callable()。
Python内置函数(2)— chr()、classmethod()、compile()、complex()、delattr()、dict()、dir()、divmod()、enumerate()、eval()。
Python内置函数(3)— exec()、filter()、float()、format()、frozenset()、getattr()、globals()、hasattr()、hash()、help()。
Python内置函数(4)— hex()、id()、input()、int()、isinstance()、issubclass、iter()、len()、list()、locals()。
Python内置函数(5)— map()、max()、memoryview()、min()、next()、object()、oct()、open()、ord()、pow()。
Python内置函数(6)— print()、property()、range()、repr()、reversed()、round()、set()、setattr()、slice()、sorted()。
Python内置函数(7)— staticmethod()、str()、sum()、super()、tuple()、type()、vars()、zip()、__import__()。

内置函数(原文)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
内置函数(中文)
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
Python内置函数.png

51、print()

a)描述

原文:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
中文:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
将值打印到流或sys中。默认stdout。
可选关键字参数:
file:类似文件的对象(流);默认为当前sys.stdout。
sep:插入值之间的字符串,默认为空格。
end:最后一个值后面的字符串,默认是一个换行符。
flush:立即吧内容输出到流文件,不作缓存。

b)语法

print() 方法的语法:print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

c)参数

objects:复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
sep:用来间隔多个对象,默认值是一个空格。
end:用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
file:要写入的文件对象。
flush:输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。

d)返回值

无。

e)实例

实例1:

print(1)
print("Hello World")
a = 1
b = 'kevin'
print(a, b)
print("aaa""bbb")
print("aaa", "bbb")
print("www", "kevin", "com", sep=".")  # 设置间隔符

运行结果:

1
Hello World
1 kevin
aaabbb
aaa bbb
www.kevin.com

实例2:

import time
print("---KEVIN EXAMPLE : Loading 效果---")
print("Loading",end = "")
for i in range(20):
    print(".",end = '',flush = True)
    time.sleep(0.5)

运行结果:

---KEVIN EXAMPLE : Loading 效果---
Loading....................

52、property()

a)描述

property() 函数的作用是在新式类中返回属性值。

b)语法

property() 方法的语法:class property([fget[, fset[, fdel[, doc]]]])

c)参数

fget:获取属性值的函数。
fset:设置属性值的函数。
fdel:删除属性值函数。
doc:属性描述信息。

d)返回值

返回新式类属性。

e)实例

定义一个可控属性值 x

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.")

如果 c 是 C 的实例化, c.x 将触发 getter,c.x = value 将触发 setter , del c.x 触发 deleter。
如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。
将 property 函数用作装饰器可以很方便的创建只读属性:

class Parrot(object):
    def __init__(self):
        self._voltage = 100000
    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

上面的代码将 voltage() 方法转化成同名只读属性的 getter 方法。
property 的 getter,setter 和 deleter 方法同样可以用作装饰器:

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

这个代码和第一个例子完全相同,但要注意这些额外函数的名字和 property 下的一样,例如这里的 x。

53、range()

a)描述

range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
list() 函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表。

b)语法

range的语法:
range(stop)
range(start, stop[, step])

c)参数

start:计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5)。
stop:计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5。
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)。

d)返回值

返回的是一个可迭代对象。

e)实例

实例1:

print("range(5):",range(5))
print("range(0, 5):",range(0, 5))
for i in range(5):
    print(i)
print("list(range(5)):",list(range(5)))
print("list(range(0)):",list(range(0)))

运行结果:

range(5): range(0, 5)
range(0, 5): range(0, 5)
0
1
2
3
4
list(range(5)): [0, 1, 2, 3, 4]
list(range(0)): []

实例2(有两个参数或三个参数的情况(第二种构造方法)):

print("list(range(0, 30, 5)):",list(range(0, 30, 5)))
print("list(range(0, 10, 2)):",list(range(0, 10, 2)))
print("list(range(0, -10, -1)):",list(range(0, -10, -1)))
print("list(range(1, 0)):",list(range(1, 0)))

运行结果:

list(range(0, 30, 5)): [0, 5, 10, 15, 20, 25]
list(range(0, 10, 2)): [0, 2, 4, 6, 8]
list(range(0, -10, -1)): [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
list(range(1, 0)): []

54、repr()

a)描述

原文:
Return the canonical string representation of the object.
For many object types, including most builtins, eval(repr(obj)) == obj.
中文:
返回对象的规范字符串表示形式。
对于许多对象类型,包括大多数内建,eval(repr(obj)) == obj。

b)语法

repr() 方法的语法:repr(object)

c)参数

object:对象。

d)返回值

返回一个对象的 string 格式。

e)实例
s = 'KEVIN'
print("repr(s):",repr(s))
dict = {'kevin': 'kevin.com', 'google': 'google.com'};
print("repr(dict):",repr(dict))

运行结果:

repr(s): 'KEVIN'
repr(dict): {'kevin': 'kevin.com', 'google': 'google.com'}

55、reversed()

a)描述

原文:
Return a reverse iterator over the values of the given sequence.
中文:
返回给定序列值的反向迭代器。

b)语法

reversed 的语法:reversed(seq)

c)参数

seq:要转换的序列,可以是 tuple, string, list 或 range。

d)返回值

返回一个反转的迭代器。

e)实例
# 字符串
seqString = 'Kevin'
print("list(reversed(seqString)):",list(reversed(seqString)))
# 元组
seqTuple = ('K', 'e', 'v', 'i', 'n')
print("list(reversed(seqTuple)):",list(reversed(seqTuple)))
# range
seqRange = range(5, 9)
print("list(reversed(seqRange)):",list(reversed(seqRange)))
# 列表
seqList = [1, 2, 4, 3, 5]
print("list(reversed(seqList)):",list(reversed(seqList)))

运行结果:

list(reversed(seqString)): ['n', 'i', 'v', 'e', 'K']
list(reversed(seqTuple)): ['n', 'i', 'v', 'e', 'K']
list(reversed(seqRange)): [8, 7, 6, 5]
list(reversed(seqList)): [5, 3, 4, 2, 1]

56、round()

a)描述

原文:
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.
中文:
将一个数字四舍五入到给定的十进制精度。
返回值是一个整数,如果ndigit被省略或没有。否则返回值的类型与数字相同。
诠释:
round() 方法返回浮点数 x 的四舍五入值,准确的说保留值将保留到离上一位更近的一端(四舍六入)。
精度要求高的,不建议使用该函数。

b)语法

round() 方法的语法:round( x [, n] )

c)参数

x:数字表达式。
n:表示从小数点位数,其中 x 需要四舍五入,默认值为 0。

d)返回值

返回浮点数x的四舍五入值。

e)实例
print ("round(70.23456):", round(70.23456))
print ("round(56.659,1):", round(56.659,1))
print ("round(80.264, 2):", round(80.264, 2))
print ("round(100.000056, 3):", round(100.000056, 3))
print ("round(-100.000056, 3):", round(-100.000056, 3))

运行结果:

round(70.23456): 70
round(56.659,1): 56.7
round(80.264, 2): 80.26
round(100.000056, 3): 100.0
round(-100.000056, 3): -100.0

57、set()。

a)描述

set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

b)语法

set 语法:class set([iterable])

c)参数

iterable -- 可迭代对象对象。

d)返回值

返回新的集合对象。

e)实例
x = set('kevin')
y = set('google')
print("x, y:",x, y)
print("x & y:",x & y)         # 交集
print("x | y:",x | y)         # 并集
print("x - y:",x - y)         # 差集

运行结果:

x, y: {'e', 'k', 'i', 'v', 'n'} {'e', 'g', 'l', 'o'}
x & y: {'e'}
x | y: {'e', 'k', 'i', 'v', 'o', 'n', 'g', 'l'}
x - y: {'n', 'v', 'k', 'i'}

58、setattr()

a)描述

原文:
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to x.y = v
中文:
将给定对象上的命名属性设置为指定值。
setattr(x, 'y', v) is equivalent to x.y = v
诠释:
setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

b)语法

setattr() 语法:setattr(object, name, value)

c)参数

object:对象。
name:字符串,对象属性。
value:属性值。

d)返回值

无。

e)实例

实例1(对已存在的属性进行赋值):

class A(object):
    bar = 1
a = A()
print("getattr(a, 'bar'):",getattr(a, 'bar'))          # 获取属性 bar 值
print("setattr(a, 'bar', 5):",setattr(a, 'bar', 5))       # 设置属性 bar 值
print("a.bar:",a.bar)

运行结果:

getattr(a, 'bar'): 1
setattr(a, 'bar', 5): None
a.bar: 5

实例2(如果属性不存在会创建一个新的对象属性,并对属性赋值):

class A():
    name = "kevin"
a = A()
print("setattr(a, 'age', 28):",setattr(a, 'age', 28))
print("a.age:",a.age)

运行结果:

setattr(a, 'age', 28): None
a.age: 28

59、slice()

a)描述

slice() 函数实现切片对象,主要用在切片操作函数里的参数传递。

b)语法

slice 语法:
class slice(stop)
class slice(start, stop[, step])

c)参数

start:起始位置
stop:结束位置
step:间距

d)返回值

返回一个切片对象。

e)实例
myslice = slice(5)    # 设置截取5个元素的切片
print("myslice:",myslice)
arr = range(10)
print("arr:",arr)
print("list(arr):",list(arr))
print("arr[myslice]:",arr[myslice])         # 截取 5 个元素
print("list(arr[myslice]):",list(arr[myslice]))         # 截取 5 个元素

运行结果:

myslice: slice(None, 5, None)
arr: range(0, 10)
list(arr): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arr[myslice]: range(0, 5)
list(arr[myslice]): [0, 1, 2, 3, 4]

60、sorted()

a)描述

原文:
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
中文:
返回一个新列表,其中包含按升序排列的iterable中的所有项。
可以提供自定义键函数来定制排序顺序,还可以设置反转标志来按降序请求结果。
诠释:
sorted() 函数对所有可迭代的对象进行排序操作。
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

b)语法

sorted 语法:sorted(iterable, key=None, reverse=False)

c)参数

iterable:可迭代对象。
key:主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse:排序规则,reverse = True 降序 , reverse = False 升序(默认)。

d)返回值

返回重新排序的列表。

e)实例

实例1():

lst = [5, 2, 3, 1, 4]
print("sorted(lst):",sorted(lst))

运行结果:

sorted(lst): [1, 2, 3, 4, 5]

实例2(也可以使用 list 的 list.sort() 方法。这个方法会修改原始的 list(返回值为None)。通常这个方法不如sorted()方便-如果你不需要原始的 list,list.sort()方法效率会稍微高一些):

lst = [5, 2, 3, 1, 4]
lst.sort()
print("lst:",lst)

运行结果:

lst: [1, 2, 3, 4, 5]

实例3(list.sort() 方法只为 list 定义,而 sorted() 函数可以接收任何的 iterable):

dic = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
print("sorted(dic):",sorted(dic))

运行结果:

sorted(dic): [1, 2, 3, 4, 5]

实例4(利用key进行倒序排序):

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list, key=lambda x: x*-1)
print("result_list:",result_list)

运行结果:

result_list: [7, 6, 5, 4, 3, 2, 1, 0]

实例5(要进行反向排序,也通过传入第三个参数 reverse=True):

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list, reverse=True)
print("result_list:",result_list)

运行结果:

result_list: [7, 6, 5, 4, 3, 2, 1, 0]

实例6(sorted 的应用,也可以通过 key 的值来进行数组/字典的排序):

array = [{"age":20,"name":"a"},{"age":25,"name":"b"},{"age":10,"name":"c"}]
array = sorted(array,key=lambda x:x["age"])
print("array:",array)

运行结果:

array: [{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]

实例7(多列排序,先按照成绩降序排序,相同成绩的按照名字升序排序):

d1 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}]
l = sorted(d1, key=lambda x:(-x['score'], x['name']))
print("l:",l)

运行结果:

l: [{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, {'name': 'bob', 'score': 18}]

你可能感兴趣的:(Python内置函数(6))