python - 为什么这段代码只能工作一半时间?

标签 python python-3.x

我有以下测试

def test_employees_not_arround_for_more_than_3_rounds(self):
    self.game_object.generate_workers()

    people_in_list_turn_1 = self.game_object.employees[:]
    self.game_object.next_turn()
    self.game_object.generate_workers()
    self.game_object.next_turn()
    self.game_object.generate_workers()
    self.game_object.next_turn()

    for employee in people_in_list_turn_1:
        self.assertFalse(employee in self.game_object.employees)

基本上,它会生成随机数量的 worker 并将其添加到我的 game_object.employees 列表中。 当我调用 game_object.next_turn 函数时,每个员工都有一个 turns_unemployed 变量,其中包含他们失业的轮数,一旦达到 3,该 worker 将被移除来自 game_object.employees 列表。

以下是 game_object.py 中的实现代码:

def generate_workers(self):
    workersToAdd = range(random.randrange(1,8))
    for i in workersToAdd:
        self.__employees.append(Employee())

def next_turn(self):
    self.__current_turn += 1
    self.__call_employees_turn_function()
    self.__remove_workers_unemployed_for_3_rounds()

def __call_employees_turn_function(self):
    for employee in self.employees:
        employee.turn()

def __remove_workers_unemployed_for_3_rounds(self):
    for employee in self.employees:
        if employee.turns_unemployed >= 3:
            self.employees.remove(employee)

我已经有一个测试来检查当 employee.turn() 被调用时 turns_unemployed 变量实际上增加了 1,所以我知道这行得通......

真正让我烦恼的是,我的测试只有 50% 的运行时间有效,而且我无法弄清楚为什么......有人看到任何可能导致任何差异的东西吗?

顺便说一句,运行 Python 3.2.2

最佳答案

您在 __remove_workers_unemployed_for_3_rounds 中迭代时正在从列表中删除项目,因此循环会跳过您希望它删除的项目。您需要迭代列表的副本。

def __remove_workers_unemployed_for_3_rounds(self):
    for employee in self.employees[:]:
        if employee.turns_unemployed >= 3:
            self.employees.remove(employee)

例子:

您每轮生成 2 个新员工。在第 4 轮,您有 2 名员工要移除(列表中的前两名)。您开始迭代并删除第一个。该列表现在只有五个项目,但迭代继续并查看第二个项目。问题是,第二个项目不再是第二个员工,而是第三个。第二名员工将保留在列表中,您的测试将失败。仅当第一轮只生成一名员工时,您的测试才有效。

关于python - 为什么这段代码只能工作一半时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8283519/

相关文章:

python - 使一些 Tkinter 列表框项目始终处于选中状态

android - Python 使用 ApkTool 和 Subprocess 反编译 APK

python - 绘制非标准轴

javascript - 嵌套函数,PHP 中的一级函数

Python 3 - 与网页交互的方式

python - 当参数在方括号中时,文档中的含义是什么?

python - 在curl中使用python字符串输出

python - 如何在Python中使用pandas在现有Excel工作表中追加列

python - 不使用正则表达式删除字符串中的标点符号和空格

python Pandas : Create Column That Acts As A Conditional Running Variable