Built-in functions
Built-in functions that give you the python, brought directly functions, such as print., Input, etc. As of version 3.6.2 python python provided a total of 68 built-in functions.
#68个内置函数
# abs() dict() help() min() setattr()
# all() dir() hex() next() slice()
# any() divmod() id() object() sorted()
# ascii() enumerate() input() oct() staticmethod()
# bin() eval() int() open() str()
# bool() 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()
# delattr() hash() memoryview() set()
1. Digital Correlation
(1) Data Types
1) bool: Boolean (True, False)
2) int: integer (integer)
3) float: floating-point (decimal)
4) complex: the complex
(2) hex conversion
1) bin () will be converted into a binary parameter
2) otc () parameter will be converted into octal
3) hex () parameter will be converted into a hexadecimal
print(bin(10)) # 二进制:0b1010
print(hex(10)) # 十六进制:0xa
print(oct(10)) # 八进制:0o12
(3) Math
1) abs () returns the absolute value
2) divmode () returns the quotient and the remainder
3) round () rounding
4) pow (a, b) of a b-th power demand, if there are three parameters. After the required number of times the third power take I
5) sum () sums
6) min () for the minimum
7) max () selecting the maximum value
print(abs(-2)) # 绝对值:2
print(divmod(20,3)) # 求商和余数:(6,2)
print(round(4.50)) # 五舍六入:4
print(round(4.51)) #5
print(pow(10,2,3)) # 如果给了第三个参数. 表示最后取余:1
print(sum([1,2,3,4,5,6,7,8,9,10])) # 求和:55
print(min(5,3,9,12,7,2)) #求最小值:2
print(max(7,3,15,9,4,13)) #求最大值:15
2. The data structure and
(1) Sequence
1) lists and tuples
list () will be converted into a list iterable
tuple () will be converted into a iterable tuple
print(list((1,2,3,4,5,6))) #[1, 2, 3, 4, 5, 6]
print(tuple([1,2,3,4,5,6])) #(1, 2, 3, 4, 5, 6)
- Built-in functions related
the reversed () will be a sequence of flip flip sequence returns an iterator
slice () slice of the list
lst = "你好啊"
it = reversed(lst) # 不会改变原列表. 返回一个迭代器, 设计上的一个规则
print(list(it)) #['啊', '好', '你']
lst = [1, 2, 3, 4, 5, 6, 7]
print(lst[1:3:1]) #[2,3]
s = slice(1, 3, 1) # 切片用的
print(lst[s]) #[2,3]
3) string
str () to convert the data to a string
print(str(123)+'456') #123456
format() 与具体数据相关, 用于计算各种小数, 精算等.
s = "hello world!"
print(format(s, "^20")) #剧中
print(format(s, "<20")) #左对齐
print(format(s, ">20")) #右对齐
# hello world!
# hello world!
# hello world!
print(format(3, 'b' )) # 二进制:11
print(format(97, 'c' )) # 转换成unicode字符:a
print(format(11, 'd' )) # ⼗进制:11
print(format(11, 'o' )) # 八进制:13
print(format(11, 'x' )) # 十六进制(⼩写字母):b
print(format(11, 'X' )) # 十六进制(大写字母):B
print(format(11, 'n' )) # 和d⼀样:11
print(format(11)) # 和d⼀样:11
print(format(123456789, 'e' )) # 科学计数法. 默认保留6位小数:1.234568e+08
print(format(123456789, '0.2e' )) # 科学计数法. 保留2位小数(小写):1.23e+08
print(format(123456789, '0.2E' )) # 科学计数法. 保留2位小数(大写):1.23E+08
print(format(1.23456789, 'f' )) # 小数点计数法. 保留6位小数:1.234568
print(format(1.23456789, '0.2f' )) # 小数点计数法. 保留2位小数:1.23
print(format(1.23456789, '0.10f')) # 小数点计数法. 保留10位小数:1.2345678900
print(format(1.23456789e+3, 'F')) # 小数点计数法. 很大的时候输出INF:1234.567890
bytes () is converted into a string bytes Type
bs = bytes("今天吃饭了吗", encoding="utf-8")
print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'
bytearray() 返回一个新字节数组. 这个数字的元素是可变的, 并且每个元素的值得范围是[0,256)
ret = bytearray("alex" ,encoding ='utf-8')
print(ret[0]) #97
print(ret) #bytearray(b'alex')
ret[0] = 65 #把65的位置A赋值给ret[0]
print(str(ret)) #bytearray(b'Alex')
the ord () to find the position of the input character with the coded characters
CHR () to find the corresponding position of the digital input character
ascii () returns that value is not in ascii code returns \ U ...
print(ord('a')) # 字母a在编码表中的码位:97
print(ord('中')) # '中'字在编码表中的位置:20013
print(chr(65)) # 已知码位,求字符是什么:A
print(chr(19999)) #丟
for i in range(65536): #打印出0到65535的字符
print(chr(i), end=" ")
print(ascii("@")) #'@'
the repr () Returns a string in the form of object
s = "今天\n吃了%s顿\t饭" % 3
print(s)
#今天
# 吃了3顿 饭
print(repr(s)) # 原样输出,过滤掉转义字符 \n \t \r 不管百分号%
#'今天\n吃了3顿\t饭'
(2) Data collection
1) Dictionary
dict create a dictionary
2) collection
Create a collection set
frozenset () to create a frozen collection. frozen collection can not add and delete operations
(3) built-in function related
Returns the number of elements in an object len ()
sorted () sort operations on iterables (Lamda)
grammar:
sorted (Iterable, key = function (collation), reverse = False)
Iterable: iterables
key: collation (sorting function), each element in the interior will be sorted iteration object parameters passed to the function to sort function of the result of calculation.
reverse: whether it is a flashback True:. flashback, False: positive sequence
lst = [5,7,6,12,1,13,9,18,5]
lst.sort() # sort是list里面的一个方法
print(lst) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
ll = sorted(lst) # 内置函数. 返回给你一个新列表 新列表是被排序的
print(ll) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
l2 = sorted(lst,reverse=True) #倒序
print(l2) #[18, 13, 12, 9, 7, 6, 5, 5, 1]
#根据字符串长度给列表排序
lst = ['one', 'two', 'three', 'four', 'five', 'six']
def f(s):
return len(s)
l1 = sorted(lst, key=f, )
print(l1) #['one', 'two', 'six', 'four', 'five', 'three']
enumerate () Gets an enumeration object collection
lst = ['one','two','three','four','five']
for index, el in enumerate(lst,1): # 把索引和元素一起获取,索引默认从0开始. 可以更改
print(index)
print(el)
# 1
# one
# 2
# two
# 3
# three
# 4
# four
# 5
# five
all () iterables in all True, result is True
any () iterables there is a True, result is True
print(all([1,'hello',True,9])) #True
print(any([0,0,0,False,1,'good'])) #True
zip () function can be used for iterative object as a parameter, the corresponding element of the object packaged into a tuple and returns a list of these tuples. If the number of elements of each iterator inconsistent, the length of the list returned and the shortest object of the same
lst1 = [1, 2, 3, 4, 5, 6]
lst2 = ['醉乡民谣', '驴得水', '放牛班的春天', '美丽人生', '辩护人', '被嫌弃的松子的一生']
lst3 = ['美国', '中国', '法国', '意大利', '韩国', '日本']
print(zip(lst1, lst1, lst3)) #<zip object at 0x00000256CA6C7A88>
for el in zip(lst1, lst2, lst3):
print(el)
# (1, '醉乡民谣', '美国')
# (2, '驴得水', '中国')
# (3, '放牛班的春天', '法国')
# (4, '美丽人生', '意大利')
# (5, '辩护人', '韩国')
# (6, '被嫌弃的松子的一生', '日本')
Fiter () filter (Lamda)
grammar:
fiter(function. Iterable)
function: function for screening will automatically pass to the elements iterable fi lter function in the left and then to determine whether to retain data in accordance with this function returns True or False, Iterable:.. iterables
def func(i): # 判断奇数
return i % 2 == 1
lst = [1,2,3,4,5,6,7,8,9]
l1 = filter(func, lst) #l1是迭代器
print(l1) #<filter object at 0x000001CE3CA98AC8>
print(list(l1)) #[1, 3, 5, 7, 9]
map () will do for the specified sequences are listed according to the mapping function provided (Lamda)
Syntax: map (function, iterable) can be mapped to iterables each element separately to perform the function.
def f(i):
return i
lst = [1,2,3,4,5,6,7,]
it = map(f, lst) # 把可迭代对象中的每一个元素传递给前面的函数进行处理. 处理的结果会返回成迭代器
print(list(it)) #[1, 2, 3, 4, 5, 6, 7]
3. Scope and relevant
locals () returns the name of the current scope
globals () Returns the name of the global scope
def func():
a = 10
print(locals()) # 当前作用域中的内容
print(globals()) # 全局作用域中的内容
print("今天内容很多")
func()
# {'a': 10}
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
# <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'
# (built-in)>, '__file__': 'D:/pycharm/练习/week03/new14.py', '__cached__': None,
# 'func': <function func at 0x0000026F8D6B97B8>}
# 今天内容很多
And 4. iterator / generator associated
range () generates data
next () iterator performs a down, with the internal real Use Next __ __ () method returns an iterator ⽅ next item
ITER () Gets iterator is actually used inside ITER __ __ () method to obtain the iterator ⽅
for i in range(15,-1,-5):
print(i)
# 15
# 10
# 5
# 0
lst = [1,2,3,4,5]
it = iter(lst) # __iter__()获得迭代器
print(it.__next__()) #1
print(next(it)) #2 __next__()
print(next(it)) #3
print(next(it)) #4
The execution of the code string type
eval () execution string types. returns the final result, and
exec () performs code string type
compile () type of code string encoded code object can be executed by the exec statement or eval () evaluated
s1 = input("请输入a+b:") #输入:8+9
print(eval(s1)) # 17 可以动态的执行代码. 代码必须有返回值
s2 = "for i in range(5): print(i)"
a = exec(s2) # exec 执行代码不返回任何内容
# 0
# 1
# 2
# 3
# 4
print(a) #None
# 动态执行代码
exec("""
def func():
print(" 我是周杰伦")
""" )
func() #我是周杰伦
code1 = "for i in range(3): print(i)"
com = compile(code1, "", mode="exec") # compile并不会执行你的代码.只是编译
exec(com) # 执行编译的结果
# 0
# 1
# 2
code2 = "5+6+7"
com2 = compile(code2, "", mode="eval")
print(eval(com2)) # 18
code3 = "name = input('请输入你的名字:')" #输入:hello
com3 = compile(code3, "", mode="single")
exec(com3)
print(name) #hello
6. O
print (): print output
input (): Gets the contents of a user output
print("hello", "world", sep="*", end="@") # sep:打印出的内容用什么连接,end:以什么为结尾
#hello*world@
7. memory-related
hash (): Get the hash value (int, str, bool, tuple) the object hash algorithm: (1) be unique object (2) dict search efficiency is very high, hash table with the space for the time consuming RAM
s = 'alex'
print(hash(s)) #-168324845050430382
lst = [1, 2, 3, 4, 5]
print(hash(lst)) #报错,列表是不可哈希的
id() : 获取到对象的内存地址
s = 'alex'
print(id(s)) #2278345368944
8. file-related operations
open (): used to open a file, create a file handle
f = open('file',mode='r',encoding='utf-8')
f.read()
f.close()
9. modules associated
__ import __ (): function for dynamically loading classes and
# 让用户输入一个要导入的模块
import os
name = input("请输入你要导入的模块:")
__import__(name) # 可以动态导入模块
10. Help
help (): function is used for a detailed description of the function or use of the module
print(help(str)) #查看字符串的用途
11. calls related
callable ():. for checking whether an object can be called, if it returns True, object likely call fails, but if it returns False calls will not succeed.
a = 10
print(callable(a)) #False 变量a不能被调用
#
def f():
print("hello")
print(callable(f)) # True 函数是可以被调用的
12. Review the built-in properties
dir (): Check built-in properties of the object, the object of the visit is __dir __ () method
print(dir(tuple)) #查看元组的方法