Python基本语法总结(三) 常用内置函数

help()函数

help() 函数用于查看函数或模块用途的详细说明。

>>> help([].append) #列表的append()函数用法
Help on built-in function append:

append(object, /) method of builtins.list instance
    Append object to the end of the list.

>>> help(hash)  #hash()函数用法
Help on built-in function hash in module builtins:

hash(obj, /)
    Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

>>> help('abc') #string用法
Squeezed text(339 lines). ....

input()函数

利用input()函数获取用户输入的字符串

str = input(tips)

input读取到的数据会以字符串的方式存入str中,tips表示提示信息,告诉用户要输入什么

a = input('请输入数字a:')
b= input('请输入数字b:')

print('a的类型为:',type(a))
print('b的类型为:',type(b))

c= int(a)+int(b)    #类型转换
print('c的类型为:',type(c))
print('c = a+b = ', c) 

输出

请输入数字a:10
请输入数字b:20
a的类型为: <class 'str'>
b的类型为: <class 'str'>
c的类型为: <class 'int'>
c = a+b =  30

可以结合map()来使用

>>> a,b,c = map(int,input().split())
10 20 30
>>> a,b,c
(10, 20, 30)
>>> 

也可以结合list使用

>>> li=[input() for i in range(5)]
1
2
3
4
5
>>> li
['1', '2', '3', '4', '5']
>>> 

print()函数

print()函数定义如下:

print (value,...,sep='',end='\n',file=sys.stdout,flush=False)
  • sep参数代表分隔符,默认为空格
  • end参数代表输出结束后的追加值,默认为换行符\n
  • file参数指定print()函数的输出目标,默认值为 sys.stdout,该默认值代表了系统标准输出,也就是屏幕,可以改变该参数让print()输出到指定文件
  • flush参数用于控制输出缓存,默认为False,一般不用管
    name = 'John'
    age = 18
    sex = 'man'
    print('Name:', name, 'Age:', 18, 'Sex:', sex)

    print('Name:', name, 'Age:', 18, 'Sex:', sex, sep='|')

    print('Name:', name, 'Age:', 18, 'Sex:', sex, end='****\n')

    f = open('D:\\test.txt', 'w')
    print('Name:', name, 'Age:', 18, 'Sex:', sex, file=f)
    f.close()

输出结果:

Name: John Age: 18 Sex: man
Name:|John|Age:|18|Sex:|man #分割符换为了'|'
Name: John Age: 18 Sex: man**** #结尾变为了'****\n'

文件被成功写入

字符串格式化输出

print() 函数使用以%开头的转换说明符对各种类型的数据进行格式化输出。

name = 'John'
age = 18
sex = 'man'

print('Name:%s'%name , 'Age:%d'%age, 'Sex:%s'%sex)
print('Name:%s Age:%d Sex:%s'%(name,age,sex))   #多个转换符对应多个表达式,记得加小括号()

运行结果:

Name:John Age:18 Sex:man
Name:John Age:18 Sex:man

类型转换函数

函数 作用
int(x) 将 x 转换成整数类型
float(x) 将 x 转换成浮点数类型
complex(real,[,imag]) 创建一个复数
str(x) 将 x 转换为字符串
repr(x) 将 x 转换为表达式字符串
eval(str) 计算在字符串中的有效 Python 表达式,并返回一个对象
chr(x) 将整数 x 转换为一个字符
ord(x) 将一个字符 x 转换为它对应的整数值
hex(x) 将一个整数 x 转换为一个十六进制字符串
oct(x) 将一个整数 x 转换为一个八进制的字符串

在类型转换时要保证传入参数有效,否则会报错,例如不能将'fff'传入int()函数中:

.
>>> int('fff')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    int('fff')
ValueError: invalid literal for int() with base 10: 'fff'
>>> 

len()函数

len() 方法返回对象(字符、列表、元组等)长度或项目个数。


>>> a=10
>>> len(a)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    len(a)
TypeError: object of type 'int' has no len()
>>> b=[1,2,3,]
>>> len(b)
3
>>> c=('a',[1,2],1.4,'ffff')
>>> len(c)
4
>>> 

range()函数

python range() 函数可创建一个整数列表,一般用在 for 循环中。
range()函数定义如下:

range(start, stop[, step])
# start:计数开始,默认为0,range(5) 等价于 range(0,5)
# stop:计数结束,区间范围为[start,stop)
# step:增加步长,默认为1
>>>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)
[]

常用写法:

for idx in range(len(list))
    #...

type()函数

函数定义如下:

type(object)
type(name, bases, dict)

传入一个参数则返回对象类型:

>>> type(1)
<class 'int'>
>>> type(1.0)
<class 'float'>
>>> type('a')
<class 'str'>

传入三个参数返回新的类型对象

id()函数

id() 函数返回对象的唯一标识符,标识符是一个整数,即所谓的地址

>>> a=10
>>> b=a
>>> id(a)
140704039180224
>>> id(b)
140704039180224
>>> a=[1,2,3]
>>> b=a # b是a的引用
>>> c=a[:]  # c是a的拷贝
>>> id(a)
2420004672192
>>> id(b)
2420004672192   # id(b) = id(a)
>>> id(c)
2420004671744   # id(c) != id(a)
>>> 

dir()函数

dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

>>> dir()   #返回当前作用域内变量、方法和定义的类型列表
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir([]) #返回列表的属性、方法列表
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

locals()函数

locals() 函数会以字典类型返回当前位置的全部局部变量

>>> a=10
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 10}
>>> 

list()函数和tuple()函数

list()函数将一个迭代器强制转换为list列表,也可以传入元组

>>> t=(1,2,3,4)
>>> list(t)
[1, 2, 3, 4]
>>> reversed(t) #迭代器
<reversed object at 0x000002301E58A850>
>>> list(reversed(t))
[4, 3, 2, 1]
>>> 

tuple()同理

sorted()函数

sorted() 函数对所有可迭代的对象进行排序操作。sorted()函数返回的是一个新的对象,而不是在原来对象上更改。

>>> li=[1,3,2,4,0]
>>> sorted(li)
[0, 1, 2, 3, 4]
>>> li
[1, 3, 2, 4, 0]
>>> 

reversed()函数

reversed()函数将序列翻转,返回一个迭代器。

>>> li
[0, 4, 2, 3, 1]
>>> reversed(li)
<list_reverseiterator object at 0x000002301E550BB0>
>>> list(reversed(li))
[1, 3, 2, 4, 0]
>>> li
[0, 4, 2, 3, 1]
>>> 

zip()函数

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。

>>> li=[1,2,3,4,5,6,7]
>>> tu=(2,3,5,4)
>>> zip(li,tu)
<zip object at 0x000002301E01DBC0>  
>>> list(zip(li,tu))
[(1, 2), (2, 3), (3, 5), (4, 4)]  # li元素个数为7,tu元素个数为4 zip()返回的列表元素个数为4
>>> 

sum()函数

sum()函数声明如下:

sum(iterable[, start])

sum()函数传入一个可迭代对象,例如列表、元组、集合,若设置参数start,则最终结果会加上start

>>> li=[1,2,3,4,5,6,7,8,9,10]
>>> sum(li)
55
>>> sum(li,10)
65
>>> 

min()函数和max()函数

min()函数返回给定参数的最小值,参数可以是序列,但是要保证各参数之间两两可以比较,也可以传入列表、元组等。

>>> min(10,20,-100) 
-100
>>> min(1,2,3.5,4)  # int 和f loat 可比较
1   
>>> min('a','b')    # str 可比较
'a' 
>>> min('a',10)     # str 和 int 不可比较
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    min('a',10)
TypeError: '<' not supported between instances of 'int' and 'str'
>>> li=[10,3,4,29,4,5]
>>> min(li) # 可传入列表
3

max()函数和min()函数同理

reduce()函数

reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是

reduce(f,[x1,x2,x3,x4]) = (f(f(x1,x2),x3),x4)

例如:

>>> from functools import reduce
>>> def add(x,y): # 定义加法函数
	return x+y

>>> reduce(add,range(1,10,2))
25
>>> def fn(x,y):  
	return x*10+y

>>> reduce(fn,range(10))  # 把序列连成int
123456789
>>> 

filter()函数

filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素,返回结果是一个迭代器Iterator,也就是一个惰性序列,若想强迫filter()完成计算结果,需要使用list()函数获取返回结果

>>> def is_odd(n):  #筛选奇数
	return n%2 ==1

>>> list(filter(is_odd,range(0,10)))
[1, 3, 5, 7, 9]
>>> def not_empty(s): # 不为空
	return s and s.strip()

>>> list(filter(not_empty,['A','','BB',None,'   ']))
['A', 'BB']
>>> 

posted @ 2020-09-09 19:53  海物chinono  阅读(236)  评论(0)    收藏  举报