2015-10-17 35 views
2

這裏是我的簡化代碼,我不能發佈我的實際代碼在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 

我該如何去做這件事?

回答

2

只需使用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)) 
+0

更好:返回 '\ n'.join('{0} {1}」格式(C,EI)爲C,EL在枚舉(自.list1,1)) – mmachine

+0

我更喜歡'枚舉'始終是基於零的,並且自己添加偏移量。我不認爲'C + 1'有任何意義的性能損失。而'c + 1'是自我解釋的。 – dopstar