Python终极武器!50个内置函数一网打尽,编程效率飙升300%!

你是不是常常羡慕Python高手们写出简洁高效的代码?实则他们的秘密武器就是Python内置函数!今天我为大家带来史上最全的50个内置函数详解,每个都配实用代码,让你从小白秒变大神!

Python终极武器!50个内置函数一网打尽,编程效率飙升300%!

先点赞+关注,Python干货不错过!

目录速览

一、基础必会(15个)
二、数据处理(12个)
三、数学运算(8个)
四、对象操作(10个)
五、高级函数(5个)


一、基础必会函数(15个)

1. print()- 输出之王

python

# 基础用法
print("Hello Python!")  # Hello Python!

# 高级用法
print("Python", "is", "awesome", sep="-", end="!!!
")
# Python-is-awesome!!!

# 格式化输出
name, age = "小明", 25
print(f"姓名:{name},年龄:{age}")  # 姓名:小明,年龄:25

2. input()- 用户交互

python

# 获取用户输入
name = input("请输入你的名字:")
print(f"欢迎你,{name}!")

# 类型转换
age = int(input("请输入年龄:"))
print(f"10年后你{age + 10}岁")

3. len()- 长度检测

python

data_list = [1, 2, 3, 4, 5]
data_str = "Python"
data_dict = {"a": 1, "b": 2}

print(len(data_list))  # 5
print(len(data_str))   # 6  
print(len(data_dict))  # 2

4. type()- 类型侦探

python

print(type(123))        # <class 'int'>
print(type(3.14))       # <class 'float'>
print(type("hello"))    # <class 'str'>
print(type([1, 2, 3]))  # <class 'list'>

# 动态类型判断
value = 100
if type(value) == int:
    print("这是整数类型")

5. str()- 字符串转换

python

num = 123
print(str(num) + "456")  # "123456"

lst = [1, 2, 3]
print("列表:" + str(lst))  # 列表:[1, 2, 3]

# 格式化
price = 99.9
print(f"价格:{str(price)}元")  # 价格:99.9元

6. int()- 整数转换

python

print(int(3.14))       # 3(向下取整)
print(int("100"))      # 100
print(int("101", 2))   # 5(二进制转十进制)

# 错误处理示例
try:
    print(int("abc"))
except ValueError:
    print("转换失败!")

7. float()- 浮点数转换

python

print(float(10))       # 10.0
print(float("3.14"))   # 3.14
print(float("1e-3"))   # 0.001

8. list()- 列表创建

python

# 字符串转列表
print(list("Python"))  # ['P', 'y', 't', 'h', 'o', 'n']

# 元组转列表
tup = (1, 2, 3)
print(list(tup))       # [1, 2, 3]

# 字典转列表(只保留键)
dict_data = {"a": 1, "b": 2}
print(list(dict_data)) # ['a', 'b']

9. tuple()- 元组创建

python

lst = [1, 2, 3]
print(tuple(lst))      # (1, 2, 3)

# 创建不可变数据
data = tuple(range(5))
print(data)           # (0, 1, 2, 3, 4)

10. dict()- 字典创建

python

# 方式1:直接创建
print(dict(name="小明", age=20))
# {'name': '小明', 'age': 20}

# 方式2:键值对列表
pairs = [("a", 1), ("b", 2)]
print(dict(pairs))    # {'a': 1, 'b': 2}

# 方式3:zip组合
keys = ["x", "y"]
values = [10, 20]
print(dict(zip(keys, values)))  # {'x': 10, 'y': 20}

11. set()- 集合创建(去重)

python

# 列表去重
nums = [1, 2, 2, 3, 3, 3]
print(set(nums))      # {1, 2, 3}

# 字符串去重
print(set("banana"))  # {'b', 'a', 'n'}

# 集合运算
set1 = set([1, 2, 3])
set2 = set([2, 3, 4])
print(set1 & set2)    # 交集:{2, 3}
print(set1 | set2)    # 并集:{1, 2, 3, 4}

12. bool()- 布尔判断

python

# 为False的情况
print(bool(0))        # False
print(bool(""))       # False
print(bool([]))       # False
print(bool({}))       # False
print(bool(None))     # False

# 为True的情况
print(bool(1))        # True
print(bool("hello"))  # True
print(bool([1]))      # True
print(bool({"a": 1})) # True

13. range()- 数字序列

python

# 基本用法
print(list(range(5)))        # [0, 1, 2, 3, 4]
print(list(range(1, 5)))     # [1, 2, 3, 4]
print(list(range(1, 10, 2))) # [1, 3, 5, 7, 9]

# 逆序
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

# 实际应用:循环
for i in range(3):
    print(f"第{i+1}次循环")

14. enumerate()- 带索引遍历

python

fruits = ['apple', 'banana', 'cherry']

# 基本用法
for i, fruit in enumerate(fruits):
    print(f"索引{i}: {fruit}")

# 指定起始索引
for i, fruit in enumerate(fruits, start=1):
    print(f"第{i}个水果: {fruit}")

15. zip()- 数据配对

python

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]

# 并行迭代
for name, score in zip(names, scores):
    print(f"{name}: {score}分")

# 创建字典
score_dict = dict(zip(names, scores))
print(score_dict)  # {'Alice': 85, 'Bob': 92, 'Charlie': 78}

# 解压
data = [(1, 'a'), (2, 'b'), (3, 'c')]
nums, letters = zip(*data)
print(nums)    # (1, 2, 3)
print(letters) # ('a', 'b', 'c')

二、数据处理函数(12个)

16. sorted()- 排序大师

python

# 列表排序
nums = [3, 1, 4, 1, 5, 9]
print(sorted(nums))           # [1, 1, 3, 4, 5, 9]

# 降序排序
print(sorted(nums, reverse=True))  # [9, 5, 4, 3, 1, 1]

# 按长度排序
words = ['python', 'java', 'c', 'javascript']
print(sorted(words, key=len))  # ['c', 'java', 'python', 'javascript']

# 复杂排序
students = [
    {'name': 'Alice', 'score': 85},
    {'name': 'Bob', 'score': 92},
    {'name': 'Charlie', 'score': 78}
]
# 按分数降序
sorted_students = sorted(students, key=lambda x: x['score'], reverse=True)
print(sorted_students)

17. reversed()- 反转序列

python

# 列表反转
lst = [1, 2, 3, 4]
print(list(reversed(lst)))  # [4, 3, 2, 1]

# 字符串反转
text = "Python"
print(''.join(reversed(text)))  # "nohtyP"

# 实际应用:判断回文
def is_palindrome(s):
    return s == ''.join(reversed(s))

print(is_palindrome("racecar"))  # True
print(is_palindrome("python"))   # False

18. map()- 映射转换

python

# 每个元素平方
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares)  # [1, 4, 9, 16]

# 多个列表映射
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
sums = list(map(lambda x, y: x + y, nums1, nums2))
print(sums)  # [5, 7, 9]

# 类型转换
str_nums = ["1", "2", "3"]
int_nums = list(map(int, str_nums))
print(int_nums)  # [1, 2, 3]

19. filter()- 数据筛选

python

# 筛选偶数
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # [2, 4, 6]

# 筛选非空字符串
words = ["", "hello", "", "world", "python"]
non_empty = list(filter(None, words))
print(non_empty)  # ['hello', 'world', 'python']

# 自定义筛选函数
def is_positive(n):
    return n > 0

numbers = [-5, 2, -8, 10, -3]
positives = list(filter(is_positive, numbers))
print(positives)  # [2, 10]

20. all()- 全真检测

python

# 检查列表所有元素为True
print(all([True, 1, "hello"]))  # True
print(all([True, 0, "hello"]))  # False(0是False)

# 实际应用:检查密码强度
def is_strong_password(password):
    conditions = [
        len(password) >= 8,
        any(c.isupper() for c in password),
        any(c.isdigit() for c in password)
    ]
    return all(conditions)

print(is_strong_password("Pass123"))  # True
print(is_strong_password("weak"))     # False

21. any()- 任一为真

python

# 检查任一元素为True
print(any([False, 0, "", "hello"]))  # True
print(any([False, 0, ""]))           # False

# 实际应用:搜索关键词
def contains_keywords(text, keywords):
    return any(keyword in text for keyword in keywords)

text = "Python programming is fun!"
keywords = ["Java", "fun", "boring"]
print(contains_keywords(text, keywords))  # True

22. sum()- 求和计算

python

# 列表求和
nums = [1, 2, 3, 4, 5]
print(sum(nums))  # 15

# 指定起始值
print(sum(nums, 10))  # 25

# 复杂求和
data = [
    {"value": 10},
    {"value": 20},
    {"value": 30}
]
total = sum(item["value"] for item in data)
print(total)  # 60

23. max()- 最大值

python

# 基本用法
nums = [3, 1, 4, 1, 5, 9]
print(max(nums))  # 9

# 按特定规则
words = ["apple", "banana", "cherry", "date"]
print(max(words, key=len))  # "banana"

# 多个参数
print(max(10, 20, 30))  # 30

# 默认值
empty_list = []
print(max(empty_list, default=0))  # 0

24. min()- 最小值

python

# 基本用法
nums = [3, 1, 4, 1, 5, 9]
print(min(nums))  # 1

# 复杂对象
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78}
]
lowest = min(students, key=lambda x: x["score"])
print(lowest)  # {'name': 'Charlie', 'score': 78}

25. abs()- 绝对值

python

print(abs(-10))     # 10
print(abs(3.14))    # 3.14
print(abs(-2.5))    # 2.5

# 实际应用:计算误差
def calculate_error(actual, predicted):
    return abs(actual - predicted)

error = calculate_error(100, 107)
print(f"误差: {error}")  # 误差: 7

26. round()- 四舍五入

python

print(round(3.14159))      # 3
print(round(3.14159, 2))   # 3.14
print(round(3.14159, 3))   # 3.142

# 银行家舍入法(四舍六入五成双)
print(round(2.5))    # 2
print(round(3.5))    # 4

# 负数的舍入
print(round(-2.5))   # -2

27. divmod()- 商和余数

python

# 基本用法
quotient, remainder = divmod(10, 3)
print(f"商: {quotient}, 余数: {remainder}")
# 商: 3, 余数: 1

# 实际应用:时间转换
def seconds_to_time(total_seconds):
    hours, remainder = divmod(total_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return hours, minutes, seconds

print(seconds_to_time(3661))  # (1, 1, 1)

三、数学运算函数(8个)

28. pow()- 幂运算

python

# 基本幂运算
print(pow(2, 3))      # 8
print(pow(2, 3, 3))   # 2 (2³ % 3)

# 浮点数幂运算
print(pow(4, 0.5))    # 2.0 (平方根)

# 与**运算符对比
print(2 ** 3)         # 8
print(2 ** 3 % 3)     # 2

29. bin()- 二进制转换

python

print(bin(10))      # '0b1010'
print(bin(255))     # '0b11111111'

# 去掉0b前缀
binary_str = bin(10)[2:]
print(binary_str)   # '1010'

# 实际应用:位操作检查
def has_bit(number, bit_position):
    return (number >> bit_position) & 1 == 1

print(has_bit(5, 0))  # True (5的二进制101,第0位是1)

30. oct()- 八进制转换

python

print(oct(8))      # '0o10'
print(oct(64))     # '0o100'

# 文件权限表明(Linux风格)
permission = 0o755
print(oct(permission))  # '0o755'

31. hex()- 十六进制转换

python

print(hex(255))    # '0xff'
print(hex(16))     # '0x10'

# 颜色值转换
def rgb_to_hex(r, g, b):
    return f"#{hex(r)[2:]:0>2}{hex(g)[2:]:0>2}{hex(b)[2:]:0>2}".upper()

print(rgb_to_hex(255, 0, 0))  # #FF0000

32. chr()- 字符转换

python

# ASCII转字符
print(chr(65))      # 'A'
print(chr(97))      # 'a'
print(chr(9731))    # '☃'(雪花符号)

# 生成字母表
alphabet = [chr(i) for i in range(65, 91)]
print(alphabet[:5])  # ['A', 'B', 'C', 'D', 'E']

33. ord()- 编码值

python

# 字符转ASCII
print(ord('A'))      # 65
print(ord('a'))      # 97
print(ord('你'))     # 20320(中文Unicode)

# 实际应用:字符距离计算
def char_distance(c1, c2):
    return abs(ord(c1) - ord(c2))

print(char_distance('a', 'd'))  # 3

34. format()- 格式化输出

python

# 数字格式化
print(format(3.14159, ".2f"))    # '3.14'
print(format(1000000, ","))      # '1,000,000'
print(format(0.25, ".0%"))       # '25%'

# 对齐格式化
print(format("Python", "<10"))   # 'Python    '
print(format("Python", ">10"))   # '    Python'
print(format("Python", "^10"))   # '  Python  '

# 进制格式化
print(format(10, "b"))           # '1010'
print(format(10, "o"))           # '12'
print(format(10, "x"))           # 'a'

35. complex()- 复数创建

python

# 创建复数
c1 = complex(3, 4)      # 3 + 4j
c2 = complex("5+6j")    # 5 + 6j

print(c1.real)          # 3.0
print(c1.imag)          # 4.0
print(c1.conjugate())   # (3-4j)

# 复数运算
c3 = c1 + c2
print(c3)               # (8+10j)

四、对象操作函数(10个)

36. id()- 对象标识

python

# 获取对象内存地址
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(id(x))          # 内存地址1
print(id(y))          # 内存地址2(不同)
print(id(z))          # 内存地址1(与x一样)

# 判断是否为同一对象
print(x is y)         # False
print(x is z)         # True

37. hash()- 哈希值

python

# 不可变对象的哈希值
print(hash("hello"))          # 哈希值1
print(hash((1, 2, 3)))        # 哈希值2
print(hash(3.14))             # 哈希值3

# 字典键必须是可哈希的
valid_dict = {
    "name": "Alice",
    123: "number",
    (1, 2): "tuple"
}

# 列表不可哈希(会报错)
try:
    hash([1, 2, 3])
except TypeError as e:
    print(f"错误: {e}")

38. isinstance()- 类型检查

python

# 基本类型检查
print(isinstance(10, int))          # True
print(isinstance(3.14, float))      # True
print(isinstance("hello", str))     # True

# 检查多个类型
value = 100
print(isinstance(value, (int, float)))  # True

# 类继承检查
class Animal: pass
class Dog(Animal): pass

dog = Dog()
print(isinstance(dog, Dog))       # True
print(isinstance(dog, Animal))    # True

39. issubclass()- 子类检查

python

class Animal: pass
class Mammal(Animal): pass
class Dog(Mammal): pass

print(issubclass(Dog, Mammal))    # True
print(issubclass(Dog, Animal))    # True
print(issubclass(Mammal, Dog))    # False

40. callable()- 可调用检查

python

# 函数是可调用的
def greet():
    return "Hello"

print(callable(greet))        # True

# 类是可调用的
class Person:
    def __init__(self, name):
        self.name = name

print(callable(Person))       # True

# 实例化后的对象,如果有__call__方法也是可调用的
class CallableClass:
    def __call__(self):
        return "I'm callable!"

obj = CallableClass()
print(callable(obj))          # True

# 普通对象不可调用
print(callable([1, 2, 3]))    # False

41. getattr()- 获取属性

python

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("小明", 25)

# 获取属性
print(getattr(person, "name"))    # 小明
print(getattr(person, "age"))     # 25

# 默认值
print(getattr(person, "height", "未知"))  # 未知

# 动态调用方法
class Calculator:
    def add(self, a, b):
        return a + b

calc = Calculator()
method = getattr(calc, "add")
result = method(10, 20)
print(result)  # 30

42. setattr()- 设置属性

python

class Person:
    pass

person = Person()

# 设置属性
setattr(person, "name", "小红")
setattr(person, "age", 20)

print(person.name)  # 小红
print(person.age)   # 20

# 动态设置多个属性
attributes = {"city": "北京", "job": "工程师"}
for key, value in attributes.items():
    setattr(person, key, value)

print(person.city)  # 北京

43. hasattr()- 检查属性

python

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

product = Product("手机", 2999)

print(hasattr(product, "name"))      # True
print(hasattr(product, "price"))     # True
print(hasattr(product, "discount"))  # False

# 安全访问
if hasattr(product, "name"):
    print(f"产品名称: {product.name}")
else:
    print("产品名称未设置")

44. delattr()- 删除属性

python

class Config:
    def __init__(self):
        self.debug = True
        self.host = "localhost"
        self.port = 8080

config = Config()
print(dir(config))  # 包含debug, host, port

# 删除属性
delattr(config, "debug")

print(hasattr(config, "debug"))  # False
print(dir(config))  # 不再包含debug

# 错误处理
try:
    delattr(config, "nonexistent")
except AttributeError as e:
    print(f"错误: {e}")

45. property()- 属性装饰器

python

class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("半径不能为负")
        self._radius = value
    
    @property
    def area(self):
        import math
        return math.pi * self._radius ** 2

circle = Circle(5)
print(circle.radius)    # 5
print(circle.area)      # 78.5398...

circle.radius = 10      # 调用setter
print(circle.area)      # 314.159...

五、高级函数(5个)

46. exec()- 动态执行

python

# 执行代码字符串
code = """
for i in range(3):
    print(f"第{i+1}次执行")
"""
exec(code)

# 传递变量
namespace = {}
exec("x = 10
y = 20
z = x + y", namespace)
print(namespace["z"])  # 30

# 实际应用:动态创建函数
function_code = """
def dynamic_func(n):
    return n * 2
"""
exec(function_code, globals())
print(dynamic_func(5))  # 10

47. eval()- 表达式求值

python

# 基本求值
print(eval("2 + 3 * 4"))          # 14
print(eval("'hello'.upper()"))    # HELLO

# 使用命名空间
x, y = 10, 20
result = eval("x + y", {"x": x, "y": y})
print(result)  # 30

# 安全限制(避免恶意代码)
import math
safe_dict = {"__builtins__": None, "math": math}
result = eval("math.sqrt(16)", safe_dict)
print(result)  # 4.0

48. compile()- 编译代码

python

# 编译简单表达式
code = compile("1 + 2 * 3", "<string>", "eval")
result = eval(code)
print(result)  # 7

# 编译多行代码
multiline_code = """
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)
"""
compiled = compile(multiline_code, "<string>", "exec")
exec(compiled)
print(factorial(5))  # 120

# 检查语法
def check_syntax(code_string):
    try:
        compile(code_string, "<string>", "exec")
        return "语法正确"
    except SyntaxError as e:
        return f"语法错误: {e}"

49. repr()- 官方表明

python

# 获取对象的官方字符串表明
lst = [1, 2, 3]
print(repr(lst))      # '[1, 2, 3]'

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p = Point(3, 4)
print(repr(p))        # Point(3, 4)

# 与str()的区别
import datetime
now = datetime.datetime.now()
print(str(now))       # 2023-10-01 12:30:45.123456
print(repr(now))      # datetime.datetime(2023, 10, 1, 12, 30, 45, 123456)

50. bytes()/ bytearray()- 字节处理

python

# bytes创建(不可变)
b = bytes([65, 66, 67])  # ASCII: A, B, C
print(b)                 # b'ABC'
print(b.decode('utf-8')) # ABC

# bytearray创建(可变)
ba = bytearray(b"hello")
ba[0] = 72  # 'H'的ASCII
print(ba)   # bytearray(b'Hello')

# 字符串编码
text = "你好"
encoded = text.encode('utf-8')
print(encoded)          # b'xe4xbdxa0xe5xa5xbd'
decoded = encoded.decode('utf-8')
print(decoded)          # 你好

# 文件操作
with open("test.bin", "wb") as f:
    f.write(bytes(range(10)))

终极实战:综合应用

案例1:数据分析管道

python

# 处理学生成绩数据
students = [
    {"name": "张三", "scores": [85, 92, 78]},
    {"name": "李四", "scores": [90, 88, 95]},
    {"name": "王五", "scores": [76, 80, 85]},
]

# 计算每个学生的平均分
averages = list(map(
    lambda s: (s["name"], sum(s["scores"]) / len(s["scores"])),
    students
))

# 找出优秀学生(平均分>85)
excellent = list(filter(lambda x: x[1] > 85, averages))

print("所有学生平均分:", dict(averages))
print("优秀学生:", excellent)

案例2:配置文件解析

python

def parse_config(config_str):
    """将字符串配置解析为字典"""
    config = {}
    for line in config_str.strip().split('
'):
        if '=' in line:
            key, value = line.split('=', 1)
            key = key.strip()
            value = value.strip()
            
            # 尝试转换为适当类型
            if value.isdigit():
                value = int(value)
            elif value.replace('.', '', 1).isdigit() and value.count('.') < 2:
                value = float(value)
            elif value.lower() in ('true', 'false'):
                value = value.lower() == 'true'
            
            setattr(config, key, value) if hasattr(config, key) else None
            config[key] = value
    return config

config_text = """
host = localhost
port = 8080
debug = true
timeout = 30.5
"""

print(parse_config(config_text))

学习路线提议

第1周:掌握前15个基础函数
第2周:学习数据处理12个函数
第3周:掌握数学和对象操作函数
第4周:挑战高级函数,完成综合项目


函数速查表

text

输出类: print, input, format
类型类: type, str, int, float, bool, list, tuple, dict, set, bytes
数学类: abs, round, pow, divmod, sum, max, min, bin, oct, hex
迭代类: range, enumerate, zip, sorted, reversed
函数类: map, filter, all, any
对象类: id, hash, isinstance, issubclass, callable
属性类: getattr, setattr, hasattr, delattr, property
高级类: exec, eval, compile, repr, chr, ord, complex

如果觉得有用,请:

  1. 点赞支持
  2. 关注我获取更多Python干货
  3. 分享给需要的小伙伴
  4. 评论告知我你想看什么内容

下期预告:Python装饰器的10种高级用法,让你的代码更优雅!

© 版权声明

相关文章

暂无评论

none
暂无评论...