"list indices must be integers or slices, not [custom class]" 但我指定了一个 int class 实例?
"list indices must be integers or slices, not [custom class]" but I'm specifying an int class instance?
我有一个自定义 class 定义如下:
class points:
def __init__(self, x=0, h=0, l=0):
self.x = x
self.h = h
self.l = l #bool location, 0 for start point, 1 for endpoint
在我的代码中,我成功地构建了这些 points
的列表,当我尝试以下条件时出现错误:
for i in points_list:
if (sorted_points[i].l == 0):
Python 认为 sorted_points[i].l
不是整数或切片(它认为它是 points
对象),但它唯一可能是整数(我什至尝试打印出 sorted_points
l
值的列表,它们都是 1 或 0),所以我很困惑。
for el in my_list
语法迭代 my_list
的元素。
看:
class A:
pass
l = [A(), A(), A()]
for el in l:
print(type(el)) # <class '__main__.A'>
所以在你的情况下你应该使用你的 i
作为点的实例。
for i in points_list:
if i.l == 0: # if it's boolean, you should even write if not i.l
...
如果你想遍历索引,使用range
for i in range(len(points_list)):
if not sorted_points[i].l:
...
我有一个自定义 class 定义如下:
class points:
def __init__(self, x=0, h=0, l=0):
self.x = x
self.h = h
self.l = l #bool location, 0 for start point, 1 for endpoint
在我的代码中,我成功地构建了这些 points
的列表,当我尝试以下条件时出现错误:
for i in points_list:
if (sorted_points[i].l == 0):
Python 认为 sorted_points[i].l
不是整数或切片(它认为它是 points
对象),但它唯一可能是整数(我什至尝试打印出 sorted_points
l
值的列表,它们都是 1 或 0),所以我很困惑。
for el in my_list
语法迭代 my_list
的元素。
看:
class A:
pass
l = [A(), A(), A()]
for el in l:
print(type(el)) # <class '__main__.A'>
所以在你的情况下你应该使用你的 i
作为点的实例。
for i in points_list:
if i.l == 0: # if it's boolean, you should even write if not i.l
...
如果你想遍历索引,使用range
for i in range(len(points_list)):
if not sorted_points[i].l:
...