Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用format方法迭代元素_Python_Class - Fatal编程技术网

Python 使用format方法迭代元素

Python 使用format方法迭代元素,python,class,Python,Class,以下是我的简化代码,因为我无法在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.

以下是我的简化代码,因为我无法在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

如何执行此操作?

只需使用
枚举
函数,如下所示:

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))

更好:返回'\n'.join('{0}{1}'。在enumerate(self.list1,1))中c,el的格式(c,el)我更喜欢
enumerate
始终以零为基础,并自己添加偏移量。我认为
c+1
没有任何显著的性能惩罚。而
c+1
是不言自明的。