我试图遍历类中的一个列表,但是只有列表的第一个成员被打印到控制台。如何打印每个元素?你知道吗
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())
循环正在
return
处理第一个字符。return
语句将阻止循环其余迭代的执行。你知道吗您可能想使用
print
而不是return
:用作:
此外,您在
class
中对characters = []
的定义是非常无用的。您正在隐藏方法调用中的class属性。你知道吗您将返回,因此是列表中的第一个元素。你知道吗
您将在第一次迭代后返回:
如果要查看所有字符,请使用print或yield并遍历
code.LoopThroughList()
或
yield
并使方法成为generator:然后:
使用yield实际上允许您使用返回的每个字符,这些字符可能更接近您在自己的代码中尝试执行的操作。你知道吗
如果您只想看到在新行上输出的每个字符,可以使用str.join公司地址:
您也不需要在
self.stringCode.upper()
上调用list,您可以直接在字符串上迭代。你知道吗相关问题 更多 >
编程相关推荐