如何使用Python中的日志记录打印列表项+整数/字符串

twf*_*wfx 5 python python-2.7

我想用项目索引打印列表项,如

0: [('idx', 10), ('degree', 0)]
1: [('idx', 20), ('degree', 0)]
Run Code Online (Sandbox Code Playgroud)

根据下面的代码,如何将'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()
Run Code Online (Sandbox Code Playgroud)

目前,结果是

DEBUG:root:[('idx', 10), ('degree', 0)]
DEBUG:root:[('idx', 20), ('degree', 0)]
Run Code Online (Sandbox Code Playgroud)

期待

DEBUG:root:0:[('idx', 10), ('degree', 0)]
DEBUG:root:1:[('idx', 20), ('degree', 0)]
Run Code Online (Sandbox Code Playgroud)

mr2*_*ert 6

我会这样做的.

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)
Run Code Online (Sandbox Code Playgroud)

这产生了这个输出:

DEBUG:root:0:[('idx', 10), ('degree', 0)]
DEBUG:root:1:[('idx', 20), ('degree', 0)]
Run Code Online (Sandbox Code Playgroud)

你也可以使用join:

message = ':'.join([str(i), str(a[i].items())])
Run Code Online (Sandbox Code Playgroud)

或格式:

message = '{0}:{1}'.format(str(i), a[i].items())
Run Code Online (Sandbox Code Playgroud)

无论你最清楚的是什么.


Vla*_*den 5

在Python> 3.6中,您可以使用fstring

logging.debug(f"{i}:{a[i].items()}")
Run Code Online (Sandbox Code Playgroud)