How to print list item + integer / string using Python entry

I would like to print a list item with an item index like

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

Based on the code below, how can I add “0:” as an 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() 

Currently, the result is

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

Expectation

 DEBUG:root:0:[('idx', 10), ('degree', 0)] DEBUG:root:1:[('idx', 20), ('degree', 0)] 
+4
source share
1 answer

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 a conclusion:

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

You can also use join:

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

Or format:

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

What is most clear to you.

+5
source

Source: https://habr.com/ru/post/1491757/


All Articles