没有这个可以做以下i吗?
for i in range(some_number):
# do something
Run Code Online (Sandbox Code Playgroud)
如果你只是想做N次,并且不需要迭代器.
哪个更pythonic?
循环:
count = 0
while count < 50:
print "Some thing"
count = count + 1
Run Code Online (Sandbox Code Playgroud)
对于循环:
for i in range(50):
print "Some thing"
Run Code Online (Sandbox Code Playgroud)
编辑:不重复,因为这有答案可以确定哪个更清晰,而不是如何在没有'i'的情况下运行范围 - 尽管最终是最优雅的
我正在尝试在python中编写一个函数,如:
def repeated(f, n):
...
Run Code Online (Sandbox Code Playgroud)
where f是一个带有一个参数的函数,n是一个正整数.
例如,如果我将square定义为:
def square(x):
return x * x
Run Code Online (Sandbox Code Playgroud)
我打来电话
repeated(square, 2)(3)
Run Code Online (Sandbox Code Playgroud)
这将是3次,2次.
正如这里所看到的,有两种方法可以多次重复某件事。但这似乎对我不起作用,所以我想知道是否有人可以提供帮助。
基本上我想重复以下3次
import random
a = []
w = 0
while w<4:
x = random.uniform(1,10)
print(x)
print(w)
a.append(w+x)
print(a)
w=w+1
Run Code Online (Sandbox Code Playgroud)
根据链接的内容,这就是我所做的,
import random
a = []
w = 0
r = 0
while r < 3:
while w<4:
x = random.uniform(1,10)
print(x)
print(w)
a.append(w+x)
print(a)
w = w+1
r += 1
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用。while 循环仅重复一次而不是三次。有人能帮我解决这个问题吗?