在Python中,可以使用sys.getsizeof()
函数来获取一个变量的字节长度。下面是一个示例代码:
import sys
def get_variable_size(variable):
size = sys.getsizeof(variable)
if isinstance(variable, str):
size -= sys.getsizeof('')
elif isinstance(variable, dict):
size -= sys.getsizeof({})
elif isinstance(variable, list):
size -= sys.getsizeof([])
elif isinstance(variable, tuple):
size -= sys.getsizeof(())
elif isinstance(variable, set):
size -= sys.getsizeof(set())
return size
# 示例变量
string_var = "Hello, world!"
int_var = 12345
list_var = [1, 2, 3, 4, 5]
dict_var = {'a': 1, 'b': 2, 'c': 3}
# 获取变量的字节长度
string_size = get_variable_size(string_var)
int_size = get_variable_size(int_var)
list_size = get_variable_size(list_var)
dict_size = get_variable_size(dict_var)
print(f"String size: {string_size} bytes")
print(f"Int size: {int_size} bytes")
print(f"List size: {list_size} bytes")
print(f"Dict size: {dict_size} bytes")
运行以上代码,将输出每个变量的字节长度。注意,对于字符串、字典和列表,需要减去相应的空初始化对象的字节长度。
上一篇:按字节分割并带有分隔符