### Python 内置函数列表及其用途
Python 提供了一系列丰富的内置函数,这些函数可以直接调用而无需额外导入模块。以下是部分常用内置函数的介绍:
#### abs()
返回数值的绝对值。
```python
print(abs(-5)) # 输出: 5
```
#### all()
如果迭代器中的所有元素都为真,则返回 `True`;否则返回 `False`。
```python
print(all([1, 2, 3])) # 输出: True
print(all([0, False, None])) # 输出: False
```
#### any()
只要有一个元素为真就返回 `True`,全部为假则返回 `False`。
```python
print(any([0, False, 'hello'])) # 输出: True
print(any([])) # 输出: False
```
#### bin()
将整数转换成二进制字符串表示形式。
```python
print(bin(8)) # 输出: 0b1000
```
#### bool()
将参数转换为布尔值,无参数时默认为 `False`。
```python
print(bool('')) # 输出: False
print(bool('hello')) # 输出: True
```
#### chr()
返回给定 Unicode 编码对应的字符。
```python
print(chr(65)) # 输出: A
```
#### dict()
创建一个新的字典对象或从其他映射或可迭代项构建字典。
```python
d = dict(a=1, b=2)
print(d) # 输出: {'a': 1, 'b': 2}
```
#### dir()
尝试返回由对象定义的有效属性列表。
```python
import math
print(dir(math))
```
#### enumerate()
返回枚举对象,默认索引从零开始计数。
```python
for i, v in enumerate(['apple', 'banana', 'orange']):
print(f'{i}: {v}')
# 输出:
# 0: apple
# 1: banana
# 2: orange
```
#### filter()
用于过滤序列,筛选出符合条件的元素组成新的列表。
```python
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # 输出: [2, 4, 6]
```
#### float(), int(), str()
分别用来把数据类型转成浮点型、整形以及字符串。
```python
f = float('3.14')
i = int('123')
s = str(456)
print(type(f), type(i), type(s)) # 输出: <class 'float'> <class 'int'> <class 'str'>
```
#### format()
格式化指定的字符串并将其写入到控制台。
```python
name = "Alice"
age = 30
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string) # 输出: Name: Alice, Age: 30
```
#### getattr(), hasattr(), setattr()
操作类实例的方法和属性。
```python
class Person:
name = "Bob"
p = Person()
print(hasattr(p, 'name')) # 输出: True
setattr(p, 'age', 25)
print(getattr(p, 'age')) # 输出: 25
```
#### help()
获取有关模块、关键字、函数的帮助文档。
```python
help(len)
```
#### input()
读取用户输入的一行文本作为字符串处理。
```python
user_input = input("Enter something:")
print(user_input)
```
#### isinstance()
判断某个变量是否是指定的数据类型。
```python
print(isinstance(5, int)) # 输出: True
print(isinstance("test", str)) # 输出: True
```
#### len()
计算容器(如字符串、元组、列表等)中元素的数量。
```python
my_list = ['red', 'green', 'blue']
length_of_my_list = len(my_list)
print(length_of_my_list) # 输出: 3
```
#### map()
应用一个函数到一系列项目上,并返回结果组成的迭代器。
```python
def square(x):
return x ** 2
nums = [1, 2, 3, 4]
result = list(map(square, nums))
print(result) # 输出: [1, 4, 9, 16]
```
#### max() 和 min()
找出最大最小值。
```python
max_value = max([1, 2, 3])
min_value = min([1, 2, 3])
print(max_value) # 输出: 3
print(min_value) # 输出: 1
```
#### open()
打开文件进行读写操作。
```python
with open('example.txt', mode='w') as f:
f.write('Hello world!')
with open('example.txt', mode='r') as f:
content = f.read()
print(content) # 输出: Hello world!
```
#### pow()
求幂运算。
```python
base = 2
exponent = 3
power_result = pow(base, exponent)
print(power_result) # 输出: 8
```
#### range()
生成不可变序列,在循环语句里经常被使用来遍历数字序列。
```python
for num in range(5):
print(num)
# 输出:
# 0
# 1
# 2
# 3
# 4
```
#### reversed()
反转任何支持顺序访问的对象的内容。
```python
reversed_sequence = ''.join(reversed('hello'))
print(reversed_sequence) # 输出: olleh
```
#### round()
四舍五入到最接近的整数或者指定位数的小数。
```python
rounded_number = round(3.14159, 2)
print(rounded_number) # 输出: 3.14
```
#### sorted()
对所有可迭代对象进行排序操作。
```python
unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(sorted_list) # 输出: [1, 1, 3, 4, 5, 9]
```
#### sum()
求数列之和。
```python
total_sum = sum([1, 2, 3, 4])
print(total_sum) # 输出: 10
```
#### tuple(), set(), frozenset(), list()
可以将其他类型的集合转化为相应的结构体。
```python
tup = tuple([1, 2, 3]) # 转换成元组
lis = list((1, 2, 3)) # 转换成列表
st = set([1, 2, 3, 3]) # 转换成集合
frz_st = frozenset(st) # 不可变集合
```
#### zip()
将多个列表对应位置打包在一起形成元组的列表。
```python
names = ["John", "Mary"]
ages = [27, 23]
paired_data = list(zip(names, ages))
print(paired_data) # 输出: [('John', 27), ('Mary', 23)]
```