python list element output

1) for loop output

This approach is most likely to think of you, and most simple, but it has a downside: its output is arranged vertically, and we often need the level of output.

>>> for i in [1,2,3]:
    print(i)
    
1
2
3

2) for loop output delimiter +

On the basis of the first method, slightly modified our output levels can be achieved, that is, the output plus separator.

>>> for i in [1,2,3]:
    print(i,end=',')
    
1,2,3,
>>> for i in [1,2,3]:
    print(i,end=' ')
    
1 2 3 

But we see this method it will have a delimiter at the end, but we generally do not need to end delimiter.

3) join string output

This approach can solve all these problems, not only to achieve the level of output, but in the end without leaving separator, the code is also more streamlined.

>>> print(" ".join(str(i) for i in [1,2,3]))
1 2 3

The above method can be applied to the case of list elements more, but less if the list of elements, then we can direct output.

>>> print(1,2,3)
1 2 3

Direct output horizontally arranged and can be done without excess end delimiter.

Guess you like

Origin www.cnblogs.com/marvin-wen/p/11884249.html