在类中迭代列表

2024-09-28 01:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历类中的一个列表,但是只有列表的第一个成员被打印到控制台。如何打印每个元素?你知道吗

class CodeManager(object):
    """Separates the input string into individual characters in a list"""

    characters = []

    def __init__(self, stringCode):
        self.stringCode = stringCode

    def LoopThroughList(self):

        self.characters = list(self.stringCode.upper())
        for chars in self.characters:
            return chars

然后在我的主Python文件中创建一个class对象:

code = CodeManager.CodeManager("Hello my name is Callum")
print (code.LoopThroughList())

Tags: inself元素列表objectdefcode成员
3条回答

循环正在return处理第一个字符。return语句将阻止循环其余迭代的执行。你知道吗

您可能想使用print而不是return

def loop_through_list(self):
    self.characters = list(self.stringCode.upper())
    for char in self.characters:
        print(char)

用作:

code = CodeManager.CodeManager("Hello my name is Callum")
code.loop_through_list()

此外,您在class中对characters = []的定义是非常无用的。您正在隐藏方法调用中的class属性。你知道吗

您将返回,因此是列表中的第一个元素。你知道吗

class CodeManager(object):
    """Separates the input string into individual characters in a list"""

    characters = []

    def __init__(self, stringCode):
        self.stringCode = stringCode

    def LoopThroughList(self):
        self.characters = list(self.stringCode.upper())
        for chars in self.characters:
            print chars

code = CodeManager("Hello my name is Callum")
code.LoopThroughList()

您将在第一次迭代后返回:

for chars in self.characters:
        return chars # ends loop

如果要查看所有字符,请使用print或yield并遍历code.LoopThroughList()

for chars in self.characters:
        print(chars)

yield并使方法成为generator

 for chars in self.characters:
        yield chars

然后:

for ch in code.LoopThroughList():
    print(ch)

使用yield实际上允许您使用返回的每个字符,这些字符可能更接近您在自己的代码中尝试执行的操作。你知道吗

如果您只想看到在新行上输出的每个字符,可以使用str.join公司地址:

self.characters = list(self.stringCode.upper())
        return "\n".join(self.characters)

您也不需要在self.stringCode.upper()上调用list,您可以直接在字符串上迭代。你知道吗

相关问题 更多 >

    热门问题