假设我有代码(虽然它没有做任何事情,只是一个例子)
def myprint():
print("foobar")
foo = random.randint(1, 6)
myprint() * foo #Obviously doesn't work
我想要它做的是执行print()
'foo'次。我该怎么做?
答案 0 :(得分:3)
您可以将代码更改为此代码:
def myprint(times):
print(times*"foobar")
foo = random.randint(1, 6)
myprint(foo)
答案 1 :(得分:2)
“pythonic”方式是for-loop:
for n in range(foo):
printfunc()
(请注意,如果您像在python 3中一样定义打印,则使用自己的方法屏蔽原始print
。
答案 2 :(得分:0)
for i in range(foo):
print('test')
如果你真的想把它当作一个表达式来回归任意(通常是非常糟糕的,或者至少是极端的hackish,形式)......
[print('test') for _ in range(foo)]
答案 3 :(得分:0)
或者,如果您想要隐瞒它并惹恼人们阅读您的代码:
import random
print('\n'.join(["foo" for _ in range(random.randint(1,6))]))
答案 4 :(得分:0)
这就是为什么你不应该调用自己的函数print
Python 3.2 (r32:88445, Dec 8 2011, 15:26:51)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
>>> def print():
... print("foobar")
...
>>> help(print)
Help on function print in module __main__:
print()
>>>
oops现在你已经覆盖了内置print
,所以你不能用它来实际打印东西了