Skip to main content
 首页 » 编程设计

python之使用格式方法遍历元素

2024年10月24日14shangdawei

这是我的简化代码,因为我无法在 python 3 中发布我的实际代码:

class example(object): 
    def __init__(self, list1): 
        self.list1 = list1 
    def __repr__(self): 
        if len(self.list1) > 0: 
            for i in self.list1: 
                for j in range(1,len(self.list1)): 
                    return ('{0:}{1:}').format(j, i) 
 
x = example(['this', 'is', 'a', 'list']) 
x 

这应该返回:

1this 

现在我希望它返回:

1this 
2is 
3a 
4list 

我该怎么做?

请您参考如下方法:

只需使用enumerate函数如下:

class example(object): 
    def __init__(self, list1): 
        self.list1 = list1 
    def __repr__(self): 
        return '\n'.join('{0}{1}'.format(c+1, el) for c, el in enumerate(self.list1))