程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 中的内置实用程序和函数

hfteth 2025-03-05 16:20:40 技术文章 14 ℃

Python 提供了丰富的内置函数集合,可简化许多常见任务。在本教程中,我们将探索这些函数,根据其功能对它们进行分类,并通过基于代码的实用示例演示它们的用法。

1. 数值函数

I. abs(x)

  • 返回数字的绝对值。
print(abs(-10))   # Output: 10
print(abs(3.14))  # Output: 3.14

II. pow(x, y)

  • x 提高到 y 的幂
print(pow(2, 3))   # Output: 8
print(pow(5, -2))  # Output: 0.04

III. round(number, ndigits])

  • 将数字四舍五入到指定的小数位数。
print(round(3.14159, 2))  # Output: 3.14
print(round(7.5))         # Output: 8

2. 序列函数

I. lne

  • 返回对象 (字符串、列表、元组等) 的长度。
print(len("Python"))      # Output: 6
print(len([1, 2, 3, 4]))  # Output: 4

II. min(可迭代)

  • 返回 iterable 中最小的项。
print(min([3, 1, 4, 1, 5]))  # Output: 1
print(min("hello"))          # Output: 'e'

III. max(可迭代)

  • 返回 iterable 中最大的项目。
print(max([3, 1, 4, 1, 5]))  # Output: 5
print(max("hello"))          # Output: 'o'

IV. sum(iterable[, start])

  • 对可迭代对象的项求和,从可选的 start 值开始。
print(sum([1, 2, 3, 4]))         # Output: 10
print(sum([1, 2, 3], start=10))  # Output: 16

3. 类型转换函数

I. int(x [, base])

  • 将数字或字符串转换为整数。
print(int(3.9))         # Output: 3
print(int("101", 2))    # Output: 5

II. 浮点型 (x)

  • 将数字或字符串转换为浮点数。
print(float(3))        # Output: 3.0
print(float("3.14"))   # Output: 3.14

III. str(对象)

  • 将对象转换为字符串。
print(str(100))        # Output: '100'
print(str([1, 2, 3]))  # Output: '[1, 2, 3]'

4. 集合函数

I. list([可迭代])

  • 将可迭代对象转换为列表。
print(list("hello"))  
# Output: ['h', 'e', 'l', 'l', 'o']

II. tuple([可迭代])

  • 将 iterable 转换为 Tuples。
print(tuple([1, 2, 3]))  
# Output: (1, 2, 3)

III. set([可迭代])

  • 将可迭代对象转换为集(删除重复项)。
print(set([1, 2, 2, 3])) 
# Output: {1, 2, 3}

IV. dict([映射])

  • 从一系列键值对创建字典。
print(dict([("a", 1), ("b", 2)]))  
# Output: {'a': 1, 'b': 2}

5. 布尔函数

I. bool[x])

  • 将值转换为布尔值。
print(bool(1))         # Output: True
print(bool(0))         # Output: False
print(bool([]))        # Output: False

6. 输入/输出函数

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

print("Hello", "World", sep="-", end="!\n")  
# Output: Hello-World!

II. input([提示])

name = input("What is your name? ")
print(f"Hello, {name}!")

7. 对象函数

一、类型(对象)

print(type(42))       # Output: 
print(type([1, 2]))   # Output: 

二、 isinstance(对象、类信息)

  • 检查对象是否为指定类或类元组的实例或子类,返回 TrueFalse
print(isinstance(42, int))       # Output: True
print(isinstance(42, str))       # Output: False

三、id(对象)

  • id() 函数返回 Python 中对象的唯一整数标识符,该标识符对应于对象的内存地址。

id() 返回相同的值时:

  1. 不可变对象:对于整数、字符串和元组等不可变对象,如果多个变量被分配相同的值,它们通常会引用同一个对象:
x = 10  
y = 10  
print(id(x) == id(y))  # True

2. 整数缓存:Python 缓存小整数(通常从 -5 到 256)。当多个变量被分配相同的小整数时,它们共享相同的内存位置:

a = 256  
b = 256  
print(id(a) == id(b))  # True

id() 返回不同的值时:

  1. 不同的对象:如果变量指向不同的对象,即使值相同,它们的 id() 值也会不同:
list1 = [1, 2, 3]  
list2 = [1, 2, 3]  
print(id(list1) == id(list2))  # False

8. 其他函数

I. help([对象])

  • 调用内置帮助系统,为指定对象或主题提供文档和使用信息。
help(sum)

输出

Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

II. dir([object])

  • 尝试返回对象的有效属性列表,这对于对象和模块的内省很有用。
print(dir([]))  

# Lists methods for the list object
['append', 'clear', 'copy', 'count', 'extend', ...]

III. eval(表达式)

  • 将字符串表达式作为 Python 代码计算并返回结果,从而允许动态执行 Python 表达式。
print(eval("3 + 5"))  
# Output: 8

IV. exec(对象)

  • 它执行提供的字符串或代码对象中包含的 Python 代码,允许动态执行代码,但通常应谨慎使用以避免安全风险。
exec("x = 5\nprint(x)")  
# Output: 5
最近发表
标签列表