在Python中单独打印一个变量的每个项目 [英] Printing each item of a variable on a separate line in Python
问题描述
我试图在Python中打印一个包含数字的列表,当它打印列表中的所有项目时,它们都打印在同一行上。
print({}.format(ports))
[60,89,200]
如何以这种形式查看结果:
60
89
我试过 print(\\\
但不起作用。
.join(ports))
我试过打印(\\\
.join(ports))但是不起作用。
。唯一的问题是,不像 print
, join
不会自动将东西转换为字符串。你必须自己做。
例如:
print (\\\
.join(map(str,ports)))
...或...
print(\\\
语句使用明确的
.join(port(port)in port))
$如果你不明白理解或者map
,那么两者是等价的*到这个:
ports_strs = []
用于端口的端口:
ports_strs.append(str port))
print(\\\
.join(ports_strs))
del ports_strs
换句话说,
map(str,ports)
会给你列表['60','89','200 ']
。
当然,写这个很漫长,如果你要为
,那么每次直接使用
print(port)
通过循环,如在jramirez的答案。
*我其实在这里作弊,两者都会给你一个迭代器,而不是那些实际上并不存在这些值的懒惰列表。但现在,我们可以假装它是一个列表。 (在Python 2.x中,它是。)
I am trying to print a list in Python that contains digits and when it prints the items in the list all print on the same line.
print ("{} ".format(ports))
here is my output
[60, 89, 200]
how can I see the result in this form:
60 89 200
I have tried
print ("\n".join(ports))
but that does not work.解决方案i have tried print ("\n".join(ports)) but does not work.
You're very close. The only problem is that, unlike
join
doesn't automatically convert things to strings; you have to do that yourself.For example:
print("\n".join(map(str, ports)))
… or …
print("\n".join(str(port) for port in ports))
If you don't understand either comprehensions or
map
, both are equivalent* to this:ports_strs = [] for port in ports: ports_strs.append(str(port)) print("\n".join(ports_strs)) del ports_strs
In other words,
map(str, ports)
will give you the list['60', '89', '200']
.Of course it would be silly to write that out the long way; if you're going to use an explicit
for
statement, you might as well justprint(port)
directly each time through the loop, as in jramirez's answer.
* I'm actually cheating a bit here; both give you an iterator over a sort of "lazy list" that doesn't actually exist with those values. But for now, we can just pretend it's a list. (And in Python 2.x, it was.)
这篇关于在Python中单独打印一个变量的每个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!