本文介绍了如何使用 Python 中的日志记录打印列表项 + 整数/字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想打印带有项目索引的列表项目,例如
I'd like to print list item with the index of item such as
0: [('idx', 10), ('degree', 0)]
1: [('idx', 20), ('degree', 0)]
根据下面的代码,如何将0:"附加为整数 + 字符串 + 列表项?
Based on the code below, how can I append '0:' as integer + string + list item?
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)]
推荐答案
我会这样做.
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)]
您也可以使用 join:
You could also use join:
message = ':'.join([str(i), str(a[i].items())])
或格式:
message = '{0}:{1}'.format(str(i), a[i].items())
什么对你来说最清楚.
这篇关于如何使用 Python 中的日志记录打印列表项 + 整数/字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!