Python核心內(nèi)置函數(shù)len()、list()、locals()實(shí)用指南解析
一、len():長度計(jì)算的"尺子"
1.1 基礎(chǔ)用法:獲取對象元素個(gè)數(shù)
len()函數(shù)返回對象的長度(元素個(gè)數(shù)),支持序列和集合等多種數(shù)據(jù)類型。
# 序列類型長度計(jì)算
string = "Hello World"
print(f"字符串長度: {len(string)}") # 輸出: 11
list_data = [1, 2, 3, 4, 5]
print(f"列表長度: {len(list_data)}") # 輸出: 5
tuple_data = (10, 20, 30)
print(f"元組長度: {len(tuple_data)}") # 輸出: 3
# 集合類型長度計(jì)算
set_data = {1, 2, 3, 2, 1} # 去重后
print(f"集合長度: {len(set_data)}") # 輸出: 3
dict_data = {'a': 1, 'b': 2, 'c': 3}
print(f"字典長度: {len(dict_data)}") # 輸出: 3
# 范圍對象
range_obj = range(1, 10)
print(f"范圍對象長度: {len(range_obj)}") # 輸出: 9
1.2 實(shí)際應(yīng)用:數(shù)據(jù)驗(yàn)證和邊界檢查
class DataValidator:
@staticmethod
def validate_input_length(data, min_len=0, max_len=None):
"""驗(yàn)證輸入數(shù)據(jù)長度"""
data_len = len(data)
if data_len < min_len:
raise ValueError(f"數(shù)據(jù)長度不能小于{min_len}")
if max_len is not None and data_len > max_len:
raise ValueError(f"數(shù)據(jù)長度不能超過{max_len}")
return True
@staticmethod
def chunk_data(data, chunk_size):
"""將數(shù)據(jù)分塊"""
if len(data) == 0:
return []
chunks = []
for i in range(0, len(data), chunk_size):
chunk = data[i:i + chunk_size]
chunks.append(chunk)
return chunks
@staticmethod
def compare_structures(struct1, struct2):
"""比較兩個(gè)數(shù)據(jù)結(jié)構(gòu)的長度"""
len1 = len(struct1) if hasattr(struct1, '__len__') else 'N/A'
len2 = len(struct2) if hasattr(struct2, '__len__') else 'N/A'
return {
'structure1_length': len1,
'structure2_length': len2,
'equal_length': len1 == len2 if isinstance(len1, int) and isinstance(len2, int) else False
}
# 使用示例
validator = DataValidator()
# 長度驗(yàn)證
try:
validator.validate_input_length("hello", min_len=3, max_len=10)
print("長度驗(yàn)證通過")
except ValueError as e:
print(f"驗(yàn)證失敗: {e}")
# 數(shù)據(jù)分塊
data = list(range(20))
chunks = validator.chunk_data(data, chunk_size=5)
print(f"數(shù)據(jù)分塊: {chunks}")
# 結(jié)構(gòu)比較
list1 = [1, 2, 3]
dict1 = {'a': 1, 'b': 2}
result = validator.compare_structures(list1, dict1)
print(f"結(jié)構(gòu)比較: {result}")
二、list():列表創(chuàng)建的"工廠"
2.1 基礎(chǔ)用法:創(chuàng)建列表對象
list()函數(shù)從可迭代對象創(chuàng)建新的列表,是Python中最常用的序列類型。
# 從字符串創(chuàng)建(字符列表)
chars = list("hello")
print(f"字符串轉(zhuǎn)列表: {chars}") # 輸出: ['h', 'e', 'l', 'l', 'o']
# 從元組創(chuàng)建
tuple_data = (1, 2, 3)
list_from_tuple = list(tuple_data)
print(f"元組轉(zhuǎn)列表: {list_from_tuple}") # 輸出: [1, 2, 3]
# 從范圍對象創(chuàng)建
numbers = list(range(5))
print(f"范圍轉(zhuǎn)列表: {numbers}") # 輸出: [0, 1, 2, 3, 4]
# 從集合創(chuàng)建(順序可能不同)
set_data = {3, 1, 4, 2}
list_from_set = list(set_data)
print(f"集合轉(zhuǎn)列表: {list_from_set}") # 輸出: [1, 2, 3, 4](順序可能變化)
# 空列表
empty_list = list()
print(f"空列表: {empty_list}") # 輸出: []
# 從字典創(chuàng)建(只獲取鍵)
dict_data = {'a': 1, 'b': 2}
keys_list = list(dict_data)
print(f"字典鍵列表: {keys_list}") # 輸出: ['a', 'b']
2.2 實(shí)際應(yīng)用:數(shù)據(jù)轉(zhuǎn)換和處理
class ListProcessor:
@staticmethod
def flatten_nested_lists(nested_list):
"""展平嵌套列表"""
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(ListProcessor.flatten_nested_lists(item))
else:
result.append(item)
return result
@staticmethod
def remove_duplicates_preserve_order(sequence):
"""去重并保持順序"""
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))]
@staticmethod
def batch_process(iterable, batch_size):
"""批量處理數(shù)據(jù)"""
items = list(iterable) # 確保是可迭代的
batches = []
for i in range(0, len(items), batch_size):
batch = items[i:i + batch_size]
batches.append(batch)
return batches
@staticmethod
def create_index_map(data):
"""創(chuàng)建值到索引的映射"""
index_map = {}
for idx, value in enumerate(list(data)):
if value not in index_map:
index_map[value] = []
index_map[value].append(idx)
return index_map
# 使用示例
processor = ListProcessor()
# 展平嵌套列表
nested = [[1, 2], [3, [4, 5]], 6]
flat = processor.flatten_nested_lists(nested)
print(f"展平結(jié)果: {flat}")
# 去重保持順序
data_with_duplicates = [3, 1, 2, 1, 4, 2, 5]
unique_ordered = processor.remove_duplicates_preserve_order(data_with_duplicates)
print(f"去重結(jié)果: {unique_ordered}")
# 批量處理
large_data = range(100)
batches = processor.batch_process(large_data, batch_size=10)
print(f"批次數(shù)量: {len(batches)}")
print(f"第一個(gè)批次: {batches[0]}")
# 索引映射
text = "hello"
index_map = processor.create_index_map(text)
print(f"字符索引映射: {index_map}")
三、locals():局部變量的"鏡子"
3.1 基礎(chǔ)用法:訪問局部命名空間
locals()函數(shù)返回當(dāng)前局部符號(hào)表的映射對象,反映當(dāng)前作用域的變量狀態(tài)。
def demonstrate_locals():
"""演示locals()函數(shù)的基本用法"""
x = 10
y = "hello"
z = [1, 2, 3]
# 獲取局部變量字典
local_vars = locals()
print("局部變量:")
for var_name, var_value in local_vars.items():
print(f" {var_name}: {var_value}")
# 修改局部變量
local_vars['x'] = 100
local_vars['new_var'] = "動(dòng)態(tài)添加"
print(f"修改后x的值: {x}") # 輸出: 100
print(f"新變量: {new_var}") # 輸出: 動(dòng)態(tài)添加
return local_vars
# 函數(shù)調(diào)用
local_dict = demonstrate_locals()
print(f"返回的局部字典: {local_dict}")
# 模塊級(jí)別的locals()(與globals()相同)
module_locals = locals()
module_globals = globals()
print(f"模塊級(jí)別locals和globals相同: {module_locals is module_globals}") # 輸出: True
3.2 實(shí)際應(yīng)用:調(diào)試和動(dòng)態(tài)編程
class DebugHelper:
def __init__(self):
self.snapshots = {}
def take_snapshot(self, snapshot_name):
"""拍攝當(dāng)前局部狀態(tài)快照"""
current_locals = locals().copy()
# 移除self參數(shù)
current_locals.pop('self', None)
self.snapshots[snapshot_name] = current_locals
return current_locals
def compare_snapshots(self, snap1_name, snap2_name):
"""比較兩個(gè)快照的差異"""
snap1 = self.snapshots.get(snap1_name, {})
snap2 = self.snapshots.get(snap2_name, {})
added = {k: v for k, v in snap2.items() if k not in snap1}
removed = {k: v for k, v in snap1.items() if k not in snap2}
changed = {}
for k in set(snap1.keys()) & set(snap2.keys()):
if snap1[k] != snap2[k]:
changed[k] = (snap1[k], snap2[k])
return {'added': added, 'removed': removed, 'changed': changed}
def dynamic_variable_management(self, **kwargs):
"""動(dòng)態(tài)變量管理"""
current_locals = locals()
print("初始局部變量:", current_locals)
# 動(dòng)態(tài)添加變量
for key, value in kwargs.items():
locals()[key] = value
print(f"已添加變量: {key} = {value}")
# 注意:在函數(shù)中修改locals()可能不會(huì)影響實(shí)際變量
# 這里主要用于演示
def test_function():
"""測試函數(shù)用于演示locals()行為"""
debugger = DebugHelper()
# 第一次快照
a = 10
b = 20
debugger.take_snapshot("第一次")
# 第二次快照(變量變化)
a = 100
c = "新變量"
debugger.take_snapshot("第二次")
# 比較差異
differences = debugger.compare_snapshots("第一次", "第二次")
print("變量變化:", differences)
# 動(dòng)態(tài)管理
debugger.dynamic_variable_management(x=1, y=2, z=3)
# 使用示例
test_function()
# 在推導(dǎo)式中的使用(Python 3.12+)
def demonstrate_comprehension_locals():
"""演示推導(dǎo)式中的locals()行為"""
external_var = "外部變量"
# 列表推導(dǎo)式
result = [locals().get('external_var') for _ in range(3)]
print(f"推導(dǎo)式中的locals(): {result}")
# 注意:在推導(dǎo)式中,locals()的行為可能因Python版本而異
demonstrate_comprehension_locals()
四、高級(jí)技巧與最佳實(shí)踐
4.1 安全使用locals()和變量管理
class SafeVariableManager:
def __init__(self):
self._protected_vars = {'self', '_protected_vars'}
def get_public_variables(self):
"""獲取公有變量(不包含保護(hù)變量)"""
current_locals = locals()
public_vars = {}
for var_name, var_value in current_locals.items():
if not var_name.startswith('_') or var_name in self._protected_vars:
public_vars[var_name] = var_value
return public_vars
def cleanup_temporary_vars(self):
"""清理臨時(shí)變量"""
current_locals = locals()
vars_to_remove = []
for var_name in current_locals:
if var_name.startswith('_temp_'):
vars_to_remove.append(var_name)
# 注意:在實(shí)際函數(shù)中,不能直接通過locals()刪除變量
# 這里返回需要?jiǎng)h除的變量名列表
return vars_to_remove
def create_variable_report(self):
"""創(chuàng)建變量狀態(tài)報(bào)告"""
current_locals = locals()
report = {
'total_variables': len(current_locals),
'variable_types': {},
'variable_details': []
}
for var_name, var_value in current_locals.items():
var_type = type(var_value).__name__
if var_type not in report['variable_types']:
report['variable_types'][var_type] = 0
report['variable_types'][var_type] += 1
report['variable_details'].append({
'name': var_name,
'type': var_type,
'value_length': len(str(var_value)) if hasattr(var_value, '__len__') else 'N/A',
'id': id(var_value)
})
return report
# 使用示例
def demonstrate_safe_management():
manager = SafeVariableManager()
# 添加一些測試變量
normal_var = "正常變量"
_temp_data = "臨時(shí)數(shù)據(jù)"
_protected_var = "保護(hù)變量"
public_vars = manager.get_public_variables()
print("公有變量:", public_vars)
report = manager.create_variable_report()
print("變量報(bào)告:", report)
temp_vars = manager.cleanup_temporary_vars()
print("需要清理的臨時(shí)變量:", temp_vars)
demonstrate_safe_management()
4.2 組合使用多個(gè)函數(shù)
def advanced_data_analysis(data_sequence):
"""高級(jí)數(shù)據(jù)分析組合使用多個(gè)函數(shù)"""
# 使用list()確保數(shù)據(jù)是可迭代的
data_list = list(data_sequence)
# 使用len()獲取基本信息
data_length = len(data_list)
print(f"數(shù)據(jù)長度: {data_length}")
# 使用locals()記錄分析狀態(tài)
analysis_state = locals().copy()
if data_length > 0:
# 基本統(tǒng)計(jì)
unique_elements = list(set(data_list))
unique_count = len(unique_elements)
analysis_state.update({
'unique_count': unique_count,
'duplicate_count': data_length - unique_count,
'unique_elements': unique_elements
})
# 動(dòng)態(tài)添加分析結(jié)果
if 'unique_count' in analysis_state:
duplication_rate = analysis_state['duplicate_count'] / data_length
analysis_state['duplication_rate'] = round(duplication_rate, 2)
return analysis_state
# 使用示例
test_data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
result = advanced_data_analysis(test_data)
print("數(shù)據(jù)分析結(jié)果:")
for key, value in result.items():
if not key.startswith('_') and key != 'analysis_state':
print(f" {key}: {value}")
def dynamic_function_builder():
"""動(dòng)態(tài)函數(shù)構(gòu)建器"""
# 獲取當(dāng)前局部變量
current_locals = locals()
# 動(dòng)態(tài)創(chuàng)建函數(shù)
function_definitions = [
('add', lambda x, y: x + y),
('multiply', lambda x, y: x * y),
('power', lambda x, y: x ** y)
]
for func_name, func in function_definitions:
current_locals[func_name] = func
print(f"已創(chuàng)建函數(shù): {func_name}")
# 測試動(dòng)態(tài)創(chuàng)建的函數(shù)
if 'add' in current_locals:
result = current_locals['add'](5, 3)
print(f"動(dòng)態(tài)函數(shù)測試: 5 + 3 = {result}")
dynamic_function_builder()
五、總結(jié)與實(shí)用建議
通過本文的詳細(xì)解析,我們深入了解了Python中三個(gè)重要的內(nèi)置函數(shù):
- len() - 長度計(jì)算的尺子
- list() - 列表創(chuàng)建的工廠
- locals() - 局部變量的鏡子
關(guān)鍵知識(shí)點(diǎn)總結(jié):
len(object)返回對象的元素個(gè)數(shù),支持大多數(shù)容器類型list(iterable)從可迭代對象創(chuàng)建新列表,是常用的序列轉(zhuǎn)換函數(shù)locals()返回當(dāng)前局部命名空間的字典,但在不同作用域中行為有差異
版本兼容性提醒:
- Python 3.12+ 中推導(dǎo)式內(nèi)的
locals()行為有變化(PEP 709) - Python 3.13+ 中優(yōu)化作用域內(nèi)的
locals()語義更加明確(PEP 667) - 注意大長度對象的
len()可能引發(fā)OverflowError
實(shí)用場景推薦:
- len():數(shù)據(jù)驗(yàn)證、邊界檢查、循環(huán)控制
- list():數(shù)據(jù)轉(zhuǎn)換、序列處理、結(jié)果收集
- locals():調(diào)試工具、動(dòng)態(tài)編程、狀態(tài)檢查
最佳實(shí)踐建議:
- 長度檢查優(yōu)先:在處理容器前先用
len()檢查大小 - 適時(shí)使用list():需要修改或多次訪問時(shí),將可迭代對象轉(zhuǎn)為列表
- 謹(jǐn)慎使用locals():主要限于調(diào)試,生產(chǎn)代碼中避免依賴其修改功能
- 異常處理:對可能的大數(shù)據(jù)使用
len()時(shí)捕獲OverflowError
安全使用注意事項(xiàng):
- 修改
locals()返回的字典可能不會(huì)影響實(shí)際變量(在函數(shù)作用域中) - 避免在性能關(guān)鍵代碼中過度使用
list()轉(zhuǎn)換 - 對用戶輸入數(shù)據(jù)使用
len()前先驗(yàn)證數(shù)據(jù)類型
進(jìn)階學(xué)習(xí)方向:
- 深入學(xué)習(xí)Python的迭代器協(xié)議和生成器表達(dá)式
- 研究
__len__()特殊方法的自定義實(shí)現(xiàn) - 了解命名空間和作用域的工作原理
- 探索
inspect模塊更強(qiáng)大的內(nèi)省功能
這三個(gè)函數(shù)雖然基礎(chǔ),但它們是Python編程的基石。合理使用它們可以讓代碼更加簡潔、清晰,特別是在數(shù)據(jù)處理、調(diào)試和元編程場景中。從簡單的長度檢查到復(fù)雜的動(dòng)態(tài)編程,掌握這些函數(shù)將顯著提升你的Python編程能力。
到此這篇關(guān)于Python核心內(nèi)置函數(shù)len()、list()、locals()的文章就介紹到這了,更多相關(guān)Python內(nèi)置函數(shù)len()、list()、locals()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 簡單介紹Python中的len()函數(shù)的使用
- Python中l(wèi)en()函數(shù)用法使用示例
- Python中的len()函數(shù)是什么意思
- Python中處理字符串的相關(guān)的len()方法的使用簡介
- Python字符串len()、split()、join()深度解析
- python 列表,數(shù)組,矩陣兩兩轉(zhuǎn)換tolist()的實(shí)例
- python列表的構(gòu)造方法list()
- 解決python使用list()時(shí)總是報(bào)錯(cuò)的問題
- Python基礎(chǔ)教程之內(nèi)置函數(shù)locals()和globals()用法分析
- 詳解Python locals()的陷阱
相關(guān)文章
詳解appium+python 啟動(dòng)一個(gè)app步驟
這篇文章主要介紹了詳解appium+python 啟動(dòng)一個(gè)app步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
python函數(shù)也可以是一個(gè)對象,可以存放在列表中并調(diào)用方式
這篇文章主要介紹了python函數(shù)也可以是一個(gè)對象,可以存放在列表中并調(diào)用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
基于Python實(shí)現(xiàn)銀行卡識(shí)別的示例代碼
銀行卡識(shí)別是一個(gè)在金融、安全等領(lǐng)域具有重要應(yīng)用的問題,本文主要為大家介紹了如何使用Python和深度學(xué)習(xí)技術(shù)來實(shí)現(xiàn)銀行卡識(shí)別功能,需要的可以參考下2024-03-03
python用matplotlib繪制二維坐標(biāo)軸,設(shè)置箭頭指向,文本內(nèi)容方式
這篇文章主要介紹了python用matplotlib繪制二維坐標(biāo)軸,設(shè)置箭頭指向,文本內(nèi)容方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Python爬蟲的兩套解析方法和四種爬蟲實(shí)現(xiàn)過程
本文想針對某一網(wǎng)頁對 python 基礎(chǔ)爬蟲的兩大解析庫( BeautifulSoup 和 lxml )和幾種信息提取實(shí)現(xiàn)方法進(jìn)行分析,及同一網(wǎng)頁爬蟲的四種實(shí)現(xiàn)方式,需要的朋友參考下吧2018-07-07

