Python3知识点查漏补缺

0. lambda匿名函数

用lambda关键词能创建小型匿名函数。这种函数得名于省略了用def声明函数的标准步骤。
lambda函数的语法只包含一个语句,如下:
lambda [arg1, arg2…argn]:expression

如下实例:

>>> sum = lambda arg1, arg2: arg1+arg2
>>> print("Value of total:", sum(10, 20))
Value of total: 30
>>> print("Value of total:", sum(20, 20))
Value of total: 40
>>> 

Lambda函数能接收任何数量的参数但只能返回一个表达式的值,匿名函数不能直接调用print,因为lambda需要一个表达式。

>>> infors = [{"name":"laowang", "age":10},{"name":"xiaoming", "age":20},{"name":"banzhang", "age":10}]
>>> infors.sort(key=lambda x:x['name'])
>>> infors
[{'name': 'banzhang', 'age': 10}, {'name': 'laowang', 'age': 10}, {'name': 'xiaoming', 'age': 20}]

1. init方法

Python3知识点查漏补缺_第1张图片

2.列表转换成字符串,字符串转换成列表

列表转换成字符串:

>>> nums = [1, 2, 9]
>>> nums = [str(i) for i in nums]
>>> nums
['1', '2', '9']
>>> n_string = "".join(nums)
>>> n_string
'129'

字符串转换成列表:

>>> n = int("".join(nums))
>>> n
129
>>> rList = [int(i) for i in list(str(n))]
>>> rList
[1, 2, 9]

3. try 和 except

num = [1,2,0,3,1.5,'6']
for x in num:
    try:  # 尝试执行下列代码
        print (6/x)
    except ZeroDivisionError:  # 当报错信息为ZeroDivisionError,执行下面的语句。
        print('0是不能做除数的!')
    except TypeError:  # 当报错信息为TypeError,执行下面的语句。
        print('被除数必须是整值或浮点数!')

结果:

6.0
3.0
0是不能做除数的!
2.0
4.0
被除数必须是整值或浮点数!

4. __call__方法

该方法的功能类似于在类中重载 () 运算符,使得类实例对象可以像调用普通函数那样,以“对象名()”的形式使用。
例子:

>>> class Comli_cn:
		# 定义__call__方法
		def __call__(self, a):
			这里的print(a)

		
>>> comli_cn = Comli_cn()
>>> comli_cn("Hello World!")
Hello World!

也就是说调用__call__方法的时候可以像调用python内置方法一样调用,对于__call__方法以下两种表达方式是一样的:

>>> comli_cn("Hello World!")
Hello World!
>>> comli_cn.__call__("Hello World!")
Hello World!

5. assert的用法

assert:断言
格式:
assert 表达式 [, 参数]
当表达式为真时,程序继续往下执行;
当表达式为假时,抛出AssertionError错误,并将 参数 输出

举例:

def foo(s):
    n = int(s)
    assert n != 0, 'n is zero!'
    return 10 / n

foo('0')

# 代码执行结果
# AssertionError: n is zero!

6. isinstance() 函数

描述

isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。

isinstance() 与 type() 区别:

    type() 不会认为子类是一种父类类型,不考虑继承关系。

    isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

语法

以下是 isinstance() 方法的语法:

isinstance(object, classinfo)

参数

object -- 实例对象。
classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。

返回值

如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。。
实例

以下展示了使用 isinstance 函数的实例:

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True

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

7. enumerate() 函数

描述

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

Python 2.3. 以上版本可用,2.6 添加 start 参数。
语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

参数

sequence -- 一个序列、迭代器或其他支持迭代对象。
start -- 下标起始位置。

返回值

返回 enumerate(枚举) 对象。

实例

以下展示了使用 enumerate() 方法的实例:

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

普通的 for 循环

>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
...     print i, seq[i]
...     i +=1
... 
0 one
1 two
2 three

for 循环使用 enumerate

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

8. bin() 函数

bin() 返回一个整数 int 或者长整数 long int 的二进制表示
用法:bin(x), x为整数 int 或者长整数 long int
例子:

>>>bin(10) 
'0b1010' 
>>>> bin(20) 
'0b10100'

9. input()函数

input() 函数接受一个标准输入数据,返回为 string 类型。
例子:

>>> a = input()
hello world!!!  # 自己输入的
>>> a
'hello world!!!'

10. split()函数

split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串。

split() 方法语法:

str.split(str="", num=string.count(str))

参数:

str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。默认为 -1, 即分隔所有。

返回值:

返回分割后的字符串列表。

例子:

>>> txt = "Google#Runoob#Taobao#Facebook"
>>> x = txt.split("#", 1)
>>> x
['Google', 'Runoob#Taobao#Facebook']

>>> y = txt.split("#", 2)
>>> y
['Google', 'Runoob', 'Taobao#Facebook']

11. map()函数

描述:

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

map() 函数语法:

map(function, iterable, ...)

参数:

function -- 函数
iterable -- 一个或多个序列

例子:


>>>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]

例子:

>>> a = input()
1 2 3 4 5
>>> a
'1 2 3 4 5'
>>> li = map(int, a.split())  # 生成一个迭代器, 这里int相当于一个函数,可以将str转为int
>>> li
<map object at 0x03539B70>
>>> for i in li:
	print(i)

	
1
2
3
4
5
>>> a = input()
1 2 3 4 5
>>> a
'1 2 3 4 5'
>>> li = list(map(int, a.split()))
>>> li
[1, 2, 3, 4, 5]

12. strip()函数

描述:

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

strip()方法语法:

str.strip([chars])

参数:

chars – 移除字符串头尾指定的字符序列。

返回值:

返回移除字符串头尾指定的字符生成的新字符串。

13. Python 字典(Dictionary) items()方法

描述:

Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

items()方法语法:

dict.items()

返回值:

返回可遍历的(键, 值) 元组数组。

例子:

>>> dic = {"a": 2, "d": 5, "c": 3}
>>> dic
{'a': 2, 'd': 5, 'c': 3}
>>> dic.items()
dict_items([('a', 2), ('d', 5), ('c', 3)])
>>> for key, value in dic.items():
    	print(key, value)

a 2
d 5
c 3

>>> dic2 = sorted(dic.items(), key=lambda x: x[0]) # 按照第0个元素排序
>>> dic2
[('a', 2), ('c', 3), ('d', 5)]

 # 按照第1个元素降序排列
>>> dic3 = sorted(dic.items(), key=lambda x: x[1], reverse = True)
>>> dic3
[('d', 5), ('c', 3), ('a', 2)]

14. enumerate()

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

例子:

>>> names = ["aa", "bb", "cc"]
>>> for temp in enumerate(names):
...     print(temp)
... 
(0, 'aa')
(1, 'bb')
(2, 'cc')
>>> for i, name in enumerate(names): # 一个拆包的过程
...     print(i, name)
... 
0 aa
1 bb
2 cc

15. 结果输出保留两位小数

>>> a = 1.23456
>>> a
1.23456
>>> print("a = %.2f" % a)
a = 1.23

16. 查看字典里是否存在某个key

>>> a = {'a': 1, 'b': 2}
>>> a
{'a': 1, 'b': 2}
>>> print(a.get('a'))
1
>>> print(a.get('c'))
None

你可能感兴趣的:(python)