跳到主要内容Python 四大内置函数:filter、float、format 与 frozenset | 极客日志Python算法
Python 四大内置函数:filter、float、format 与 frozenset
Python 内置函数 filter、float、format、frozenset 是开发中的高频工具。filter 用于惰性过滤迭代器,支持 None 参数;float 处理数值转换及科学计数法;format 提供灵活的字符串对齐与精度控制;frozenset 创建不可变集合以作字典键。文章涵盖基础用法、类封装实践、版本差异及性能优化建议,强调异常处理与类型安全,帮助开发者提升代码质量与效率。
SecGuard13 浏览 filter():数据过滤的'智能筛子'
filter() 函数利用指定函数过滤可迭代对象,只保留返回真值的元素。在 Python 3 中它返回一个迭代器,这意味着它是惰性求值的,非常适合处理大数据流。
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}")
这里有个小技巧:当 function 参数为 None 时,filter 会直接剔除所有假值(如 0、空字符串、None),相当于 (item for item in iterable if item)。
实战场景:数据清洗和验证
在实际项目中,我们常把 filter 封装进工具类来处理复杂逻辑。
class DataCleaner:
@staticmethod
def remove_outliers():
((threshold_func, data))
():
():
(email, ) email email.split()[-]
((is_valid_email, email_list))
():
(( x: (x, target_type), data))
cleaner = DataCleaner()
numbers = [, , , , , , ]
normal_numbers = cleaner.remove_outliers(numbers, x: x < )
()
emails = [, , , ]
valid_emails = cleaner.validate_emails(emails)
()
mixed_data = [, , , [, ], , ]
strings_only = cleaner.filter_by_type(mixed_data, )
()
data, threshold_func
"""移除异常值"""
return
list
filter
@staticmethod
def
validate_emails
email_list
"""验证邮箱格式(简单版本)"""
def
is_valid_email
email
return
isinstance
str
and
'@'
in
and
'.'
in
'@'
1
return
list
filter
@staticmethod
def
filter_by_type
data, target_type
"""按类型过滤数据"""
return
list
filter
lambda
isinstance
10
15
100
12
8
200
14
lambda
50
print
f"正常数值:{normal_numbers}"
"invalid"
"test@domain"
print
f"有效邮箱:{valid_emails}"
1
"hello"
3.14
1
2
"world"
42
str
print
f"仅字符串:{strings_only}"
float():数值转换的'精确天平'
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()}")
安全转换与数据处理
用户输入往往不可靠,直接转换容易报错。建议封装安全转换逻辑。
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():字符串格式化的'魔术师'
format() 函数将值转换为格式化字符串,支持丰富的选项,比 f-string 更灵活地处理动态格式。
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')}")
报表生成与自定义格式化
在处理报表或日志时,format() 能帮我们快速构建整齐的输出。
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():不可变集合的'保险箱'
frozenset() 创建不可变的集合对象。既然不可变,它就可以作为字典的键或包含在其他集合中,这是普通 set 做不到的。
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}")
数据去重与集合运算
不可变集合常用于配置管理或查找表,确保数据不被意外修改。
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()
版本变更与兼容性说明
不同 Python 版本间这些函数的行为略有差异,开发时需留意。
filter() 函数
始终是核心内置函数,但在 Python 3 中返回迭代器(Python 2 返回列表),这影响内存占用。
- 3.6 版本起支持数字分组下划线:
float('1_000_000.5')。
- 3.7 版本起参数变为仅限位置形参。
- 3.8 版本起,若
__float__() 未定义,会回退至 __index__()。
print(f"分组数字:{float('1_000_000.5')}")
class CustomNumber:
def __index__(self):
return 42
custom_num = CustomNumber()
print(f"回退转换:{float(custom_num)}")
format() 函数的版本变更
3.4 版本起,当 format_spec 不是空字符串时,object().__format__(format_spec) 会触发 TypeError,强制子类实现该方法。
frozenset() 函数
从 Python 2.4 开始引入,API 始终保持稳定。
最佳实践与实用技巧
安全使用建议
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'[^\d.-]', '', 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}")
性能优化技巧
- filter() 代替列表推导式:处理大数据时,
filter 的惰性求值特性更节省内存。
- 避免不必要的 float() 调用:先检查类型再转换。
- frozenset() 用于快速查找:集合查找是 O(1) 复杂度,适合大规模数据去重或存在性检查。
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()
总结与实用建议
这四个内置函数覆盖了数据处理的核心环节:过滤、转换、展示和存储。
- filter():数据清洗、条件过滤、异常值处理。注意其返回迭代器。
- float():用户输入处理、科学计算、数据转换。务必做好异常捕获。
- format():报表生成、数据展示、国际化格式化。比 f-string 更适合动态格式。
- frozenset():配置管理、查找表、集合运算。需要不可变性时的首选。
float() 在 3.7+ 版本中参数变为仅限位置形参。
format() 在 3.4+ 版本中对空对象有更严格的错误处理。
- 使用数字分组下划线需要 Python 3.6+。
- 深入学习
functools 模块的函数式编程工具。
- 研究
decimal 模块进行精确小数计算。
- 探索
collections 模块的更多数据结构。
- 了解格式化字符串字面值(f-string)的使用。
掌握这些函数的特性和最佳实践,能显著提升代码质量和开发效率。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,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