Python 使用format方法迭代元素
以下是我的简化代码,因为我无法在python 3中发布我的实际代码: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.
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
是不言自明的。