Is there any one function for printing iteration values

Suppose I have any iterable

var = "ABCDEF"

I get iterable like

it = itertools.combinations(var,2)

is there any single function to print all iteration values ​​like

printall(it)

instead of using a for loop

+6
source share
4 answers

It depends on what you want, if you want to print all the values, you need to calculate them - iterability does not guarantee that the values ​​are calculated until they are requested, so the easiest way to achieve this is to make a list :

 print(list(iterable)) 

This will print items in the usual list format, which may be suitable. If you want each item to appear on a new line, the best option is, as you said, a simple loop:

 for item in iterable: print(item) 

If you do not need data in a specific format, but you just need to read (not everything on one line, for example), you can check the pprint module .

The last option, which I really don’t feel, is optimal, but mention of completeness is possible in 3.x, where the print() function is very flexible:

 print(*iterable, sep="\n") 

Here we unpack print() iterated as arguments, and then divide the separator into a new line (as opposed to regular space).

+14
source

You can use the str.join method and join each iterable element in a new line.

 print('\n'.join(it)) 
+4
source

You can use a format that will allow each element to be shaped as you wish:

 >>> print '\n'.join('{:>10}'.format(e) for e in iter([1,2,'1','2',{1:'1'}])) 1 2 1 2 {1: '1'} 

Each element does not have to be a string, but it must have a __repr__ method if it is not a string.

Then you can easily write the desired function:

 >>> def printall(it,w): print '\n'.join('{:>{w}}'.format(e,w=w) for e in it) >>> printall([1,2,'3','4',{5:'6'}],10) 1 2 3 4 {5: '6'} 

I use a list, but any iterable will do.

+1
source

You can use chain () from itertools to create an iterator for the var data, and then simply unzip it using the * iterator statement

 >>> from itertools import chain >>> var = 'ABCDEF' >>> print(*chain(var)) ABCDEF >>> print(*chain(var), sep='\n') A B C D E F 

If you just need to iterate over existing data and print it again, you can use the asterisk * operator to do this

 >>> print(*var) ABCDEF >>> print(*var, sep='\n') A B C D E F 
0
source

All Articles