2013-07-17 111 views
4
使用記錄整數/字符串

我想與項目,例如索引打印列表項爲如何打印列表項+在Python

0: [('idx', 10), ('degree', 0)] 
1: [('idx', 20), ('degree', 0)] 

基於下面的代碼,我怎麼能追加「0 :'作爲整數+字符串+列表項?

import logging 

class Node(object): 
    __slots__= "idx", "degree" 

    def __init__(self, idx, degree): 
     self.idx = idx 
     self.degree = 0 


    def items(self): 
     "dict style items" 
     return [ 
      (field_name, getattr(self, field_name)) 
      for field_name in self.__slots__] 

def funcA(): 

    a = [] 
    a.append(Node(10, 0)) 
    a.append(Node(20, 0)) 

    for i in range(0, len(a)): 
     logging.debug(a[i].items()) 

if __name__ == '__main__': 
    logging.basicConfig(level=logging.DEBUG) 
    funcA() 

目前,結果是

DEBUG:root:[('idx', 10), ('degree', 0)] 
DEBUG:root:[('idx', 20), ('degree', 0)] 

期待

DEBUG:root:0:[('idx', 10), ('degree', 0)] 
DEBUG:root:1:[('idx', 20), ('degree', 0)] 

回答

5

我會做這樣的。

def funcA(): 
    a = [] 
    a.append(Node(10, 0)) 
    a.append(Node(20, 0)) 

    for i in range(0, len(a)): 
     message = '%s:%s' % (i, a[i].items()) 
     logging.debug(message) 

將會產生這樣的輸出:

DEBUG:root:0:[('idx', 10), ('degree', 0)] 
DEBUG:root:1:[('idx', 20), ('degree', 0)] 

您還可以使用加入:

message = ':'.join([str(i), str(a[i].items())]) 

或格式:

message = '{0}:{1}'.format(str(i), a[i].items()) 

無論是最清楚你。