跳到主要内容Python 四大内置函数详解:filter、float、format、frozenset | 极客日志Python算法
Python 四大内置函数详解:filter、float、format、frozenset
本文详细介绍了 Python 四个重要内置函数:filter() 用于数据过滤,float() 用于数值转换,format() 用于字符串格式化,frozenset() 用于创建不可变集合。文章包含基础用法、实际应用案例(如数据清洗、报表生成)、版本兼容性说明及最佳实践建议。通过代码示例展示了各函数的特性,如 filter 的惰性求值、float 的科学计数法支持、format 的对齐选项以及 frozenset 作为字典键的能力。旨在帮助开发者掌握这些工具以提升代码质量和效率。
1.1 基础用法:基于条件过滤元素
filter() 函数使用指定函数来过滤可迭代对象中的元素,只保留函数返回真值的元素。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"偶数:{even_numbers}")
mixed_data = [0, 1, False, True, None, "hello", "", 3.14]
truthy_values = list(filter(None, mixed_data))
print(f"真值元素:{truthy_values}")
1.2 实际应用:数据清洗和验证
class DataCleaner:
@staticmethod
def remove_outliers(data, threshold_func):
"""移除异常值"""
return list(filter(threshold_func, data))
@staticmethod
def validate_emails(email_list):
"""验证邮箱格式(简单版本)"""
def is_valid_email(email):
return isinstance(email, str) and '@' in email and '.' in email.split('@')[-1]
return list(filter(is_valid_email, email_list))
@staticmethod
def filter_by_type(data, target_type):
"""按类型过滤数据"""
return list(filter(lambda x: isinstance(x, target_type), data))
cleaner = DataCleaner()
numbers = [10, 15, 100, 12, 8, 200, 14]
normal_numbers = cleaner.remove_outliers(numbers, lambda x: x < 50)
print(f"正常数值:{normal_numbers}")
emails = ["[email protected]", "invalid", "test@domain", "[email protected]"]
valid_emails = cleaner.validate_emails(emails)
print(f"有效邮箱:{valid_emails}")
mixed_data = [1, "hello", 3.14, [1, 2], "world", 42]
strings_only = cleaner.filter_by_type(mixed_data, str)
print(f"仅字符串:{strings_only}")
二、float():数值转换的"精确天平"
2.1 基础用法:创建浮点数
float() 函数从数字或字符串创建浮点数,支持多种输入格式。
print(f"从整数创建:{float(42)}")
print(f"从浮点数创建:{float(3.14)}")
print(f"带符号字符串:{float('+1.23')}")
print(f"带空格字符串:{float(' -12345\n')}")
print(f"科学计数法:{float('1e-003')}")
print(f"大写科学计数法:{float('+1E6')}")
print(f"无穷大:{float('-Infinity')}")
print(f"NaN: {float('nan')}")
print(f"无穷大:{float('inf')}")
print(f"无参数:{float()}")
2.2 实际应用:安全数值转换和数据处理
class SafeFloatConverter:
@staticmethod
def safe_float_conversion(value, default=0.0):
"""安全转换为浮点数"""
try:
return float(value)
except (ValueError, TypeError):
return default
@staticmethod
def parse_numeric_strings(string_list):
"""从字符串列表中解析数值"""
def try_convert(s):
try:
return float(s)
except (ValueError, TypeError):
return None
converted = filter(lambda x: x is not None, map(try_convert, string_list))
return list(converted)
@staticmethod
def validate_float_range(value, min_val=None, max_val=None):
"""验证浮点数范围"""
try:
num = float(value)
if min_val is not None and num < min_val:
return False
if max_val is not None and num > max_val:
return False
return True
except (ValueError, TypeError):
return False
converter = SafeFloatConverter()
test_values = ["3.14", "invalid", "99.9", None, "1e2"]
safe_results = [converter.safe_float_conversion(v) for v in test_values]
print(f"安全转换结果:{safe_results}")
numeric_strings = ["123", "45.67", "1e-3", "not_a_number", "-999"]
parsed_numbers = converter.parse_numeric_strings(numeric_strings)
print(f"解析后的数值:{parsed_numbers}")
values_to_check = [10, "25.5", "1000", "-5", "invalid"]
for val in values_to_check:
is_valid = converter.validate_float_range(val, min_val=0, max_val=100)
print(f"{val} 在 0-100 范围内:{is_valid}")
三、format():字符串格式化的"魔术师"
3.1 基础用法:值格式化
format() 函数将值转换为格式化字符串,支持丰富的格式化选项。
print(f"整数格式化:{format(12345, ',')}")
print(f"浮点数格式化:{format(3.14159, '.2f')}")
print(f"百分比格式化:{format(0.256, '.1%')}")
print(f"右对齐:{format('hello', '>10')}")
print(f"左对齐:{format('world', '<10')}")
print(f"居中对齐:{format('test', '^10')}")
print(f"零填充:{format(42, '05d')}")
print(f"十六进制:{format(255, 'x')}")
print(f"八进制:{format(64, 'o')}")
print(f"二进制:{format(10, 'b')}")
value = 3.1415926
print(f"str() 版本:{str(value)}")
print(f"format() 版本:{format(value, '.3f')}")
3.2 实际应用:自定义格式化和报表生成
class ReportFormatter:
@staticmethod
def format_currency(amount, currency_symbol='¥'):
"""格式化货币金额"""
return format(amount, f'{currency_symbol},.2f')
@staticmethod
def format_percentage_data(values):
"""格式化百分比数据"""
return [format(val, '.2%') for val in values]
@staticmethod
def create_aligned_table(data, column_widths):
"""创建对齐的表格数据"""
formatted_rows = []
for row in data:
formatted_cells = []
for i, cell in enumerate(row):
width = column_widths[i]
if isinstance(cell, (int, float)):
formatted = format(cell, f'>{width}')
else:
formatted = format(str(cell), f'<{width}')
formatted_cells.append(formatted)
formatted_rows.append(' '.join(formatted_cells))
return formatted_rows
@staticmethod
def format_scientific_data(numbers, precision=3):
"""格式化科学数据"""
return [format(num, f'.{precision}e') for num in numbers]
formatter = ReportFormatter()
amounts = [1234.56, 7890.12, 45.67, 1000000]
currency_formatted = [formatter.format_currency(amt) for amt in amounts]
print(f"货币格式化:{currency_formatted}")
percentages = [0.1234, 0.5678, 0.9876]
percent_formatted = formatter.format_percentage_data(percentages)
print(f"百分比数据:{percent_formatted}")
table_data = [["产品", "销量", "增长率"], ["手机", 1500, 0.25], ["电脑", 800, 0.15], ["平板", 1200, 0.30]]
aligned_table = formatter.create_aligned_table(table_data, [10, 8, 10])
print("对齐表格:")
for row in aligned_table:
print(row)
scientific_data = [1234567, 0.000123, 987654321]
sci_formatted = formatter.format_scientific_data(scientific_data)
print(f"科学计数法:{sci_formatted}")
四、frozenset():不可变集合的"保险箱"
4.1 基础用法:创建不可变集合
frozenset() 函数创建不可变的集合对象,适合作为字典键或集合元素。
fset1 = frozenset([1, 2, 3, 4, 5])
print(f"从列表创建:{fset1}")
fset2 = frozenset("hello")
print(f"从字符串创建:{fset2}")
fset3 = frozenset(range(5))
print(f"从范围创建:{fset3}")
empty_fset = frozenset()
print(f"空集合:{empty_fset}")
dict_with_frozenset = {
frozenset([1, 2, 3]): "集合 1",
frozenset([4, 5, 6]): "集合 2"
}
print(f"字典键示例:{dict_with_frozenset}")
4.2 实际应用:数据去重和集合运算
class SetOperations:
@staticmethod
def create_immutable_lookup_table(data_list):
"""创建不可变查找表"""
unique_items = frozenset(data_list)
return {item: index for index, item in enumerate(unique_items)}
@staticmethod
def find_common_elements(*sequences):
"""查找多个序列的共同元素"""
if not sequences:
return frozenset()
sets = [frozenset(seq) for seq in sequences]
common = sets[0]
for s in sets[1:]:
common = common.intersection(s)
return common
@staticmethod
def create_immutable_config(config_dict):
"""创建不可变配置"""
frozen_config = {}
for key, value in config_dict.items():
if isinstance(value, (list, set)):
frozen_config[key] = frozenset(value)
else:
frozen_config[key] = value
return frozen_config
@staticmethod
def set_operations_example():
"""集合运算示例"""
A = frozenset([1, 2, 3, 4, 5])
B = frozenset([4, 5, 6, 7, 8])
print(f"集合 A: {A}")
print(f"集合 B: {B}")
print(f"并集:{A.union(B)}")
print(f"交集:{A.intersection(B)}")
print(f"差集 (A-B): {A.difference(B)}")
print(f"对称差集:{A.symmetric_difference(B)}")
operations = SetOperations()
data = ["apple", "banana", "apple", "cherry", "banana"]
lookup_table = operations.create_immutable_lookup_table(data)
print(f"查找表:{lookup_table}")
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [5, 6, 7, 8, 9]
common = operations.find_common_elements(list1, list2, list3)
print(f"共同元素:{common}")
config = {
"allowed_users": ["user1", "user2", "user3"],
"permissions": {"read", "write"},
"max_connections": 100
}
frozen_config = operations.create_immutable_config(config)
print(f"不可变配置:{frozen_config}")
operations.set_operations_example()
五、版本变更与兼容性说明
5.1 各函数的版本演进
- 始终是 Python 的核心内置函数
- 在 Python 3 中返回迭代器(Python 2 中返回列表)
print(f"分组数字:{float('1_000_000.5')}")
class CustomNumber:
def __index__(self):
return 42
custom_num = CustomNumber()
print(f"回退转换:{float(custom_num)}")
try:
result = object().__format__('s')
print(f"对象格式化:{result}")
except TypeError as e:
print(f"格式化错误:{e}")
- 从 Python 2.4 开始引入
- 始终保持稳定的 API
六、最佳实践与实用技巧
6.1 安全使用建议
class BestPractices:
@staticmethod
def safe_data_processing():
"""安全数据处理示例"""
def safe_filter_function(func, iterable):
def wrapper(item):
try:
return func(item)
except Exception:
return False
return filter(wrapper, iterable)
def robust_float_conversion(value):
"""健壮的浮点数转换"""
if value is None:
return 0.0
try:
return float(value)
except (ValueError, TypeError):
if isinstance(value, str):
cleaned = value.strip()
import re
cleaned = re.sub(r'[^Ù.-]', '', cleaned)
try:
return float(cleaned)
except ValueError:
pass
return 0.0
def safe_format(value, format_spec):
"""安全的格式化函数"""
try:
return format(value, format_spec)
except (ValueError, TypeError):
return str(value)
return {
'safe_filter': safe_filter_function,
'robust_float': robust_float_conversion,
'safe_format': safe_format
}
practices = BestPractices()
tools = practices.safe_data_processing()
data = [1, 2, "3", "invalid", 5]
safe_result = list(tools['safe_filter'](lambda x: x > 2, data))
print(f"安全过滤结果:{safe_result}")
test_values = ["123.45", "$99.99", "1,000.50", "invalid"]
converted = [tools['robust_float'](v) for v in test_values]
print(f"健壮转换结果:{converted}")
format_test = [1000, "hello", 3.14159]
formatted = [tools['safe_format'](v, ',.2f') for v in format_test]
print(f"安全格式化:{formatted}")
6.2 性能优化技巧
def performance_tips():
"""性能优化建议"""
large_data = range(1000000)
filtered_data = filter(lambda x: x % 2 == 0, large_data)
def efficient_numeric_processing(numbers):
processed = []
for num in numbers:
if isinstance(num, (int, float)):
processed.append(num * 1.1)
else:
try:
processed.append(float(num) * 1.1)
except ValueError:
processed.append(0.0)
return processed
large_set = frozenset(range(1000000))
print(f"查找性能测试:{999999 in large_set}")
return "性能优化技巧演示完成"
performance_tips()
七、总结与实用建议
通过本文的详细解析,我们深入了解了四个重要的 Python 内置函数:
- filter() - 数据过滤的智能筛子
- float() - 数值转换的精确天平
- format() - 字符串格式化的魔术师
- frozenset() - 不可变集合的保险箱
filter(func, iterable) 惰性过滤元素,支持 None 函数
float(x) 从数字或字符串创建浮点数,支持科学计数法
format(value, spec) 灵活格式化值,支持对齐、精度等选项
frozenset(iterable) 创建不可变集合,适合作为字典键
- 注意 float() 在 3.7+ 版本中变为仅限位置参数
- format() 在 3.4+ 版本中对空对象有更严格的错误处理
- 使用数字分组下划线需要 Python 3.6+
- filter():数据清洗、条件过滤、异常值处理
- float():用户输入处理、科学计算、数据转换
- format():报表生成、数据展示、国际化格式化
- frozenset():配置管理、查找表、集合运算
- 始终验证输入:特别是在使用 float() 转换用户输入时
- 使用异常处理:包装 filter() 和 float() 调用
- 选择合适的数据结构:需要不可变性时使用 frozenset()
- 考虑性能影响:大数据集使用 filter() 的惰性求值特性
- 深入学习 functools 模块的函数式编程工具
- 研究 decimal 模块进行精确小数计算
- 探索 collections 模块的更多数据结构
- 了解格式化字符串字面值(f-string)的使用
这些内置函数是 Python 编程的基础工具,掌握它们的特性和最佳实践将显著提升代码质量和开发效率。
微信扫一扫,关注极客日志
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown 转 HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
- HTML 转 Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online