Python 中 TypeError: object of type 'int' has no len() 错误
当我们将整数传递给 len()
函数时,会出现 Python“TypeError: object of type 'int' has no len() ”。 要解决该错误,需要将整数转换为字符串,例如 len(str(my_int))
或更正分配并将序列(list
, str
等)传递给 len()
函数。
下面是一个产生上述错误的示例
my_int = 100
# ⛔️ TypeError: object of type 'int' has no len()
print(len(my_int))
我们将一个整数传递给导致错误的 len()
函数。
如果需要获取整数的长度,先将其转换为字符串。
my_int = 100
print(len(str(my_int))) # 👉️ 3
len()
函数返回对象的长度(项目数)。
my_list = ['apple', 'banana', 'kiwi']
result = len(my_list)
print(result) # 👉️ 3
该函数采用的参数可以是序列(字符串、元组、列表、范围或字节)或集合(字典、集合或冻结集合)。
请注意
,不能使用整数调用len()
函数。
如果我们不希望变量存储整数值,则必须更正赋值。
如果我们尝试迭代特定次数,请使用 range()
类。
my_int = 5
for n in range(my_int):
print(n)
result = list(range(my_int))
# 👇️ [0, 1, 2, 3, 4]
print(result)
range 类通常用于在 for 循环中循环特定次数,并采用以下参数:
- start 表示范围开始的整数(默认为 0)
- stop 直到,但不包括提供的整数
- step 范围将由从开始到结束的每 N 个数字组成(默认为 1)
请注意
,当我们将一个对象传递给len()
函数时,会调用该对象的__len__()
方法。
我们可以使用 dir()
函数打印对象的属性并查找 __len__
属性。
my_int = 5
print(dir(my_int))
或者我们可以使用 try/except
语句进行检查。
my_int = 5
try:
print(my_int.__len__)
except AttributeError:
# 👇️ this runs
print('object has no attribute __len__')
我们尝试在 try 块中访问对象的 __len__
属性,如果引发 AttributeError
,我们知道该对象没有 __len__
属性,无法传递给 len()
函数。
如果我们不确定变量存储什么类型,请使用内置的 type()
类。
my_int = 5
print(type(my_int)) # 👉️ <class 'int'>
print(isinstance(my_int, int)) # 👉️ True
类型类返回对象的类型。
如果传入的对象是传入类的实例或子类,则 isinstance
函数返回 True。
总结
当我们将整数传递给 len()
函数时,会出现 Python“TypeError: object of type 'int' has no len()”。 要解决该错误,请将整数转换为字符串,例如 len(str(my_int))
或更正分配并将序列(list
, str
等)传递给 len()
函数。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。