问题
A = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]
I am trying my best to print A
of the form:
1 2 3
2 3 4
4 5 6
That is in different lines, but I am unable to do so without all the elements in different lines. This is my code so far:
for r in A:
for t in r:
print(t,)
print
This is my output:
1
2
3
2
3
4
4
5
6
It seems really simple, and I think a minor change would do it. Thanks!
回答1:
Use a simple for loop and " ".join()
mapping each int
in the nested list to a str
with map()
.
Example:
>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
... print(" ".join(map(str, xs)))
...
1 2 3
4 5 6
7 8 9 10
The difference here is that we can support arbitrary lengths of inner lists.
The reason your example did not work as expected is because your inner loop is iterating over each element of the sub-list;
for r in A: # r = [1, 2, 3]
for t in r: # t = 1 (on first iteration)
print(t,)
print
And print()
by default prints new-line characters at the end unless you use: print(end="")
I believe if you were using Python 2.x print t,
would work. For example:
>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
... for x in xs:
... print x,
... print
...
1 2 3
4 5 6
7 8 9 10
But print(x,)
would not work as you intended it; Python 2.x or 3.x
回答2:
for r in A:
print '%d %d %d' % tuple(r)
回答3:
Method-1 :
We can use list comprehension and .join()
operator.
>>> my_list = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]
>>> for item in my_list:
print ' '.join(str(x) for x in item)
1 2 3
2 3 4
4 5 6
Method-2 :
>>> my_list = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]
>>> for item in my_list:
for x in item:
print x,
print
1 2 3
2 3 4
4 5 6
Inner print
with a comma ensures that inner list's elements are printed in a single line.
Outer print
ensures that for the next inner list, it prints in next line.
回答4:
print
without trailing comma will print a newline character.
for r in A:
for t in r:
print t,
print
回答5:
The same question was answered by Jim Fasarakis Hilliard in Print list of lists in separate lines.
In Python 3.x we can use:
A = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]
for i in A:
print(*i)
And the corresponding output is:
1 2 3
2 3 4
4 5 6
回答6:
I wonder why nobody listed this short and pythonic way:
for row in A:
print(*row)
回答7:
If you are in Python 3.x:
print(*('{} {} {}'.format(*r) for r in A), sep='\n')
or:
print(*('%d %d %d' % tuple(r) for r in A), sep='\n')
If not, you can import Python 3.x's print function from the __future__
module.
回答8:
for [a,b,c] in A:
print(a,b,c)
This might help. But if you have more number of elements in the lists or if elements in the nested lists are variable,This won't work. Below code will print all elements in a nested line in single line.
for b in A:
for p in b:
print(p,end=" ")
print()
来源:https://stackoverflow.com/questions/30521975/print-a-nested-list-line-by-line-python