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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17690057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:55:28  来源:igfitidea点击:

How to print list item + integer/string using logging in Python

pythonpython-2.7

提问by twfx

I'd like to print list item with the index of item such as

我想打印带有项目索引的列表项目,例如

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

Based on the code below, how can I append '0:' as integer + string + list item?

根据下面的代码,我如何将 '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()

Currently, result is

目前,结果是

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

Expecting

期待

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

采纳答案by mr2ert

I would do it like this.

我会这样做。

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)

Which produces this as output:

产生这个作为输出:

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

You could also use join:

您还可以使用 join:

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

Or format:

或格式:

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

Whatever is the most clear to you.

什么对你来说都是最清楚的。

回答by Vlad Bezden

with Python > 3.6 you can use fstring

使用 Python > 3.6 你可以使用fstring

logging.debug(f"{i}:{a[i].items()}")