[英]Python - Shorter way to print these variables
If I have five variables - each named var0, var1, var2, var3, var4 is there a shorter way to print these than typing out print(var0), print(var1) etc. for each one?如果我有五个变量——每个变量都命名为 var0、var1、var2、var3、var4,是否有比为每个变量键入 print(var0)、print(var1) 等更短的打印方法? Perhaps a for loop?
也许是一个for循环? Somewhat new to python.
对python有点新。 I have something I'm trying to create.
我有一些我想创造的东西。 If this is possible it should get me where I need to be.
如果这是可能的,它应该让我到达我需要去的地方。
Edit: They are dynamic variables, so none of those solutions would work.编辑:它们是动态变量,所以这些解决方案都不起作用。 It could be var1-5 or var1-25.
它可以是 var1-5 或 var1-25。
If you have a list of values you can join them together with a separator.如果您有一个值列表,您可以使用分隔符将它们连接在一起。
>>> print('\n'.join(['a', 'b', 'c', 'd'])
a
b
c
d
The new print()
function in Python 3.x takes a sep
keyword argument which is used to separate the contents passed to print()
. Python 3.x 中的新
print()
函数采用sep
关键字参数,用于分隔传递给print()
的内容。 This can be used to separate the output of each of your variables by newlines - as if they were being printed separately:这可用于通过换行符分隔每个变量的输出 - 就好像它们是单独打印的一样:
>>> var1, var2, var3, var4 = 1, 2, 3, 4
>>> print(var1, var2, var3, var4, sep='\n')
1
2
3
4
>>>
Just do print(var1, var2, var3, var 4, sep='\\n')
.只需执行
print(var1, var2, var3, var 4, sep='\\n')
。 It should print them out with a blank line inbetween.它应该打印出来,中间有一个空行。
This command will work without change, even if you have var1
up to var99999
.即使您拥有
var1
到var99999
,此命令也无需更改即可var99999
。
import re
print(["{} = {}".format(v, eval(v)) for v in dir() if re.match('var.*', v)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.