1. map() 函数
map()函数会将其第一个参数(函数)应用到可迭代对象的每一个元素上,并返回一个迭代器,该迭代器包含应用函数后的结果
ll = [1, 2, 3, 4, 5, 6, 7]
def index(x):
return x ** 2 # x的2次方
res = map(index, ll)
res = map(lambda x: x ** 2, ll) # 第一个参数使用匿名函数
print(list(res)) # [1, 4, 9, 16, 25, 36, 49]
2. zip() 函数 - 拉链
它主要用于将多个可迭代对象(如列表、元组等)作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的zip对象,Python 3.x以上,需要转换为list、tuple等才能直接查看内容
l1 = [1, 2, 3, 4, 5, 6]
l2 = ['a', 'b', 'c', 'd']
l3 = ['kevin', 'jerry', 'tank', 'oscar']
l4 = ['kevin1', 'jerry2', 'tank3', 'oscar4']
res = zip(l1, l2)
res1 = zip(l1, l2, l3)
res2 = zip(l1, l2, l3, l4)
print(list(res))
print(tuple(res1))
print(list(res2))
结果:
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
((1, 'a', 'kevin'), (2, 'b', 'jerry'), (3, 'c', 'tank'), (4, 'd', 'oscar'))
[(1, 'a', 'kevin', 'kevin1'), (2, 'b', 'jerry', 'jerry2'), (3, 'c', 'tank', 'tank3'), (4, 'd', 'oscar', 'oscar4')]
3. filter() 函数
用于过滤序列,过滤掉那些不符合条件的元素,返回由符合条件True元素组成的新迭代器
接收两个参数:
第一个参数是一个函数,这个函数用于判断序列中的元素是否符合条件(即返回True或False)
第二个参数是一个序列(可以是列表、元组、字符串等可迭代对象)
ll = [11, 22, 33, 44, 55, 66]
def index(x):
return x > 30
# res = filter(index, ll) # 内部也是for循环
# print(list(res)) # [33, 44, 55, 66]
res1 = filter(lambda x: x > 30, ll)
print(list(res1)) # [33, 44, 55, 66]
4.abs() 函数
作用是返回其参数的绝对值。
它可以接受多种类型的参数,例如整数、浮点数、复数等,并返回相应的绝对值
print(abs(-10)) # 输出: 10
print(abs(10.5)) # 输出: 10.5
print(abs(-3 + 4j)) # 输出: (3+4j) 因为复数的绝对值是模
5. chr() 函数
chr() 函数接受一个整数作为参数,并返回对应的 ASCII 字符
如果传入的整数超出了 ASCII 码的范围,Python 会引发一个 ValueError
A~Z: 65~96
a~z:97~122
print(chr(65)) # 输出: 'A' A~Z:65~96
print(chr(97)) # 输出: 'a'` a~z:97~122
6. callable() 函数
用于检查一个对象是否可调用,如果一个对象是可调用的,那么它就可以像函数一样被调用
可调用的对象通常包括函数、方法、类实例(如果该类定义了__call__()方法)
# 定义一个可调用的函数
def my_function():
print("Hello, world!")
class MyClass:
def test(self):
pass
# 定义一个可调用的类,该类实现了__call__方法
class MyCallableClass:
def __call__(self):
print("This class can be called!")
# 检查函数是否可调用
print(callable(my_function)) # 输出:True
# 检查类实例是否可调用
instance = MyCallableClass()
print(callable(instance)) # 输出:True
# 检查普通类是否可调用
print(callable(MyClass)) # 输出:True
print(callable(None)) # 输出:False
print(callable([])) # 输出:False
7. hasattr() 函数
用于检查对象是否具有指定的属性。如果对象具有该属性,则返回 True,否则返回 False
还可以用来检查模块、类或类型是否有指定的属性或方法。
class MyClass:
def __init__(self):
self.attr = "I exist!"
obj = MyClass()
# 检查obj是否有名为'attribute'的属性
print(hasattr(obj, 'attr')) # 输出:True
# 检查obj是否有名为'attribute'的属性
print(hasattr(obj, 'attribute')) # 输出:False
8. isinstance() 函数
用于判断一个对象是否是一个已知的类型,或者该对象是否属于一个类的实例(或该类的子类的一个实例)
这个函数对于动态类型检查非常有用,尤其是在处理继承和多态时
class TestIsinstance:
pass
obj = TestIsinstance()
# 检查obj是否是MyClass的实例
print(isinstance(obj, TestIsinstance)) # 输出:True
# 检查obj是否是list的实例
print(isinstance(obj, list)) # 输出:False
# 还可以用来检查基本类型,如字符串、整数等。
value = 13
if isinstance(value, (int, float)):
print('是的')
9. iter() 函数
iter()方法用于获取一个迭代器,允许你一次次访问集合中的一个元素,直到遍历完整个集合
iter() 可以接受两个参数:
iterable(必须):一个可迭代对象,如列表(list)、元组(tuple)、字符串(str)等。
sentinel(可选):用于控制迭代何时结束
my_list = [1, 2, 3, 4, 5]
iter1 = iter(my_list)
print(next(iter1)) # 1
print(next(iter1)) # 2
# 使用两个参数(示例)
def count():
num = 0
while True:
yield num
num += 1
# 创建一个迭代器,当count()返回的值等于5时停止迭代
it = iter(count().__next__, 5)
# 使用迭代器
print(next(it)) # 输出 0
print(next(it)) # 输出 1
print(next(it)) # 输出 2
print(next(it)) # 输出 3
print(next(it)) # 输出 4
print(next(it)) # 报错:StopIteration,因为下一个值将是5,与sentinel相等
10. repr() 函数
repr()方法可以用于获取不同类型的对象(如类、实例等)的表示字符串
class MyRepr:
def __init__(self, name):
self.name = name
my_instance = MyRepr("test")
print(repr(MyRepr)) # 输出: <class '__main__.MyClass'>
print(repr(my_instance)) # 输出: <__main__.MyClass object at 0x10271f3d0>
11. enumerate() 函数
用于枚举序列(如列表、元组、字符串等)中的元素,返回一个包含索引和元素的元组
在 Python 3.3以上,enumerate() 成为内置函数,无需导入任何模块
for index, value in enumerate(['a', 'b', 'c']): # index, value: 索引,值
print(index, value)
# 输出:
# 0 a
# 1 b
# 2 c
for index, value in enumerate({'key1': 1, 'key2': 2}): # index, value:索引、值
print(index, value)
# 输出 - 字典只循环key值
# 0 key1
# 1 key2
12. bin() 函数
函数用于将一个整数转换成其二进制表示的字符串形式,返回的字符串以 '0b'
开头
a = bin(1)
b = bin(2)
c = bin(4)
d = bin(8)
print(a)
print(b)
print(c)
print(d)
# 输出:
# 0b1
# 0b10
# 0b100
# 0b1000
13. any() 函数
判断序列中的所有元素是否都为False,如果有一个为True,则返回True
a = [False, False, False, False]
b = [False, True]
c = {True, False, False}
print(any(a)) # False
print(any(b)) # True
print(any(c)) # True
14. sort() 函数
只能对列表类型的数字或字母进行排序
reverse
用于指定排序是升序(False
)还是降序(True
)
a = [8, 5, 4, 7]
a.sort() # 升序
print(a) # [4, 5, 7, 8]
a.sort(reverse=True) # 降序
print(a) # [8, 7, 5, 4]
a = ['a', 'c', 'd', 'b']
a.sort() # 升序
print(a) # ['a', 'b', 'c', 'd']
a.sort(reverse=True) # 降序
print(a) # ['d', 'c', 'b', 'a']
a = ['你', '好', '呀']
a.sort() # 升序
print(a) # ['你', '呀', '好']
a.sort(reverse=True) # 降序
print(a) # ['好', '呀', '你']
15. sorted()
函数
与sort()使用方法类似,可以对字符串,字典进行操作
如果你需要保留原列表不变,可以使用 sorted()
函数
它接受与 sort()
方法相同的参数,但返回一个新的列表
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 1, 2, 3, 4, 5, 9]
print(numbers) # 原数据输出: [3, 1, 4, 1, 5, 9, 2]
a = [['a', 'c', 'B'], ['d', 'e', 'A'], ['c', 'g', 'f']]
print(sorted(a, key=lambda x: x[1])) # 根据第三个元素进行排序
b = {'小白': 14, '大黄': 26, '阿狗': 40}
print(sorted(b.items(), key=lambda x: x[1])) # 按照第二个元素进行排序
c = 'ccbaderthb'
print(sorted(c, reverse=True)) # 降序排序,返回列表形式
# 输出:
# [['a', 'c', 'B'], ['d', 'e', 'A'], ['c', 'g', 'f']]
# [('小白', 14), ('大黄', 26), ('阿狗', 40)]
# ['t', 'r', 'h', 'e', 'd', 'c', 'c', 'b', 'b', 'a']
16. find() 函数
find()
函数用于在字符串中查找子字符串
str.find(sub[, start[, end]]):
sub
-- 指定检索的字符串。
start
-- 可选参数,开始查找的位置。默认为0
end
-- 可选参数,结束查找的位置。默认为字符串的长度
返回结果:
如果找到子字符串,则返回子字符串的最低索引
如果没有找到,则返回-1
s = "hello world"
print(s.find("world")) # 输出: 6
print(s.find("world", 7)) # 输出: -1,因为从索引7开始查找,未找到
print(s.find("hello")) # 输出: 0
print(s.find("python")) # 输出: -1,因为未找到
17.index() 函数
index()
函数与find()
函数类似,也是用于在字符串中查找子字符串,但如果未找到子字符串,则会抛出一个ValueError
异常,而不是返回-1
str.index(sub[, start[, end]]):
sub
-- 指定检索的字符串。
start
-- 可选参数,开始查找的位置。默认为0
end
-- 可选参数,结束查找的位置。默认为字符串的长度
返回结果:
如果找到子字符串,则返回子字符串的最低索引
如果没有找到,则抛出ValueError
异常
s = "hello world"
print(s.index("world")) # 输出: 6
print(s.index("hello")) # 输出: 0
# 下面的代码会抛出ValueError异常
try:
print(s.index("python"))
except ValueError:
print("子字符串未找到")
18. count() 函数
用于统计字符串中某个子字符串出现的次数,或者列表中某个元素出现的次数
这个函数返回子字符串或元素在父字符串或列表中出现的次数
对于列表(以及其他一些可迭代对象),count()
方法会计算某个元素在列表中出现的次数
str.count(sub[, start[, end]]):
sub
-- 要搜索的子字符串
start
-- 可选参数,搜索的起始位置。默认为0
end
-- 可选参数,搜索的结束位置。默认为字符串的长度
s = "hello world, hello everyone"
print(s.count("hello")) # 输出: 2
print(s.count("world", 0, 10)) # 输出: 1,只在索引0到10之间查找
print(s.count("python")) # 输出: 0,因为未找到
lst = [1, 2, 2, 3, 4, 4, 4]
print(lst.count(2)) # 输出: 2
print(lst.count(4)) # 输出: 3
print(lst.count(5)) # 输出: 0,因为未找到
19. split() 函数
按照指定字符分割字符串,返回的是数组格式
a = 'aavv,vvvc,s,?'
# 默认全部分割数据
print(a.split(',')) # ['aavv', 'vvvc', 's?']
# 只需要分割前出现的两次分割符
print(a.split(',',2)) # ['aavv', 'vvvc', 's,?']
20. join() 函数
用一个字符或子串合并字符串,即是将多个字符串合并成一个新的字符串
a = 'hello'
b = ' '.join(a)
c = '/'.join(a)
print(b) # h e l l o
print(c) # h/e/l/l/o