【问题标题】:Removing classes from list in Python从 Python 列表中删除类
【发布时间】:2015-09-10 10:28:22
【问题描述】:

为什么我可以删除列表中的字符串但不能删除类?如果列表中有课程,可以这样做吗?这样做的正确方法是什么?

class Temp():
    def __init__(self, name, name2):
        self.n = name
        self.n2 = name2

cltemp1 = Temp("1", "2")
cltemp2 = Temp("3", "4")

x = ["1", "2"]
clx = [cltemp1, cltemp2]


def remove_string_from_class():
    global x

    for x[:] in x:
        del x[0]

remove_string_from_class()

print x


def remove_class_from_list():
    global clx

    for clx[:] in clx:
        del clx[0]

remove_class_from_list()

print clx

TypeError:只能分配一个可迭代对象

【问题讨论】:

  • for clx[:] in clxfor x[:] in x 是什么意思?
  • 与早期函数中的 x[:] 相同。我想要它的意思是:对于列表 clx 中的每个元素,删除此列表中的第一个元素,直到它为空。
  • 你可能得试试for c in clx[:]:
  • while clx 也可以。我很好奇,for x[:] in x 是从哪里来的?它看起来确实适用于字符串列表,但我以前没见过。

标签: python class python-2.7 python-3.x del


【解决方案1】:

要从列表中删除每个项目,只需使用lst = []。如果您需要改变列表对象而不重新分配它,您可以改用lst[:] = []

至于为什么你的版本不行:

您以错误的方式迭代列表。迭代应该看起来像for var in lst。您的函数在字符串列表上工作的事实大多是偶然的:它将x[:] 替换为第一个字符串,然后删除该字符串。它不适用于所有值(例如x = ['11', '22']),并且如您所见,当列表包含不可迭代时它会出错。

【讨论】:

  • 感谢您的帮助。它甚至比以前的答案更快
【解决方案2】:

请尝试从列表中删除元素

def remove_class_from_list():
    global clx
    for c in clx[:]:
        clx.remove(c)

【讨论】:

  • 这是一个非常低效的 (O(n^2)) 和 unpythonic 方法来做ctx = []
【解决方案3】:

或者您可以将这两种方法添加到您的类中:

def __iter__(self):
    return self

def next(self):
    if getattr(self, 'done', None):
        raise StopIteration
    self.done = True
    return 5

但我建议你从python.org上的一些在线教程中正确学习python

【讨论】:

  • 主要是为了激励用户学习迭代器和迭代器。引发的异常和伴随的错误消息可能会让他感到好奇。
猜你喜欢
  • 2023-04-03
  • 2020-01-23
  • 1970-01-01
  • 2017-11-02
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
相关资源
最近更新 更多