如何遍历Python中的类对象列表

时间:2018-11-26 20:26:27

标签: python loops iterator

我试图遍历类对象/模块对象的列表以检查冲突,并抛出此错误:

  File "C:/Users/travi/PycharmProjects/game/main.py", line 81, in <module>
if collision.collision1.is_collision(player.player1.vel, player.player1.x1, player.player1.x2, player.player1.y1, player.player1.y2, environmentVector[i].x1, environmentVector[i].x2, environmentVector[i].y1, environmentVector[i].y2):
TypeError: list indices must be integers or slices, not environment

此处是代码(来自main.py)

    for i in environmentVector:
        if collision.collision1.is_collision(player.player1.vel, player.player1.x1, player.player1.x2, player.player1.y1, player.player1.y2, environmentVector[i].x1, environmentVector[i].x2, environmentVector[i].y1, environmentVector[i].y2):
            print("collision")

environment.py:

import pygame

class environment():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.x1 = x - 16
        self.x2 = x + 16
        self.y1 = y - 16
        self.y2 = y + 16

collision.py:

import pygame
import player
import enemy
import environment

class collision():
    def __init__(self):
        self.collision = False

    def is_collision(self, moveSpeed, x1, x2, y1, y2, X1, X2, Y1, Y2):
        if (((x2 + moveSpeed >= X1) and (x2 <= X2)) and (((y2 >= Y1) and (y2 <= Y2)) or ((y1 <= Y2) and (y1 >= Y1)))) or (((x1 - moveSpeed <= X2) and (x1 >= X1)) and (((y2 >= Y1) and (y2 <= Y2)) or ((y1 <= Y2) and (y1 >= Y1)))):
            return True
        else:
            return False

1 个答案:

答案 0 :(得分:2)

Python for循环是“ for-each”类型的循环,这与C语言和某些其他语言中的传统for循环不同。在每次迭代中,循环变量(在您的情况下为i)是容器中的下一个元素。 假设vecstd::vector<int>类型,在C ++中是这样的:

for (size_t i = 0; i != vec.size(); ++i){
    std::cout << vec[i] << std::endl;
}

在Python中大致等效(假定lstlist对象):

for i in lst:
    print(i)

您可以看到i是元素本身,而不是它的索引。

话虽如此,这就是固定您的for循环的方式:

for i in environmentVector:
    if collision.collision1.is_collision(player.player1.vel, player.player1.x1, player.player1.x2, player.player1.y1, player.player1.y2, i.x1, i.x2, i.y1, i.y2):
        print("collision")

请注意,我仅用environmentVector[i]个替换了i个。

如果您绝对需要索引,则可以使用enumerate
(再次假定lstlist对象):

for indx, obj in enumerate(lst):
    print(indx, obj)

在这里,在每次迭代中,您都将获得分配给indx的索引和分配给obj的对象本身