python-在同一元素上重复
在python中,有没有标准的方法来重复相同的元素 例如,我有这样一个:python-在同一元素上重复,python,python-3.x,Python,Python 3.x,在python中,有没有标准的方法来重复相同的元素 例如,我有这样一个: for i in range(1, 5): if some_function(i) fails: reiterate_with_i 当然,我可以在for循环中编写一个while循环,但是是否有任何内置的for循环?不,python的for循环中没有任何内置的for循环允许这样做。while循环是标准的方式 i = 1 while i <= 5: if some_function(i
for i in range(1, 5):
if some_function(i) fails:
reiterate_with_i
当然,我可以在for循环中编写一个while循环,但是是否有任何内置的for循环?不,python的for循环中没有任何内置的for循环允许这样做。while循环是标准的方式
i = 1
while i <= 5:
if some_function(i) fails:
continue
else:
i += 1
i=1
而我最接近的同源词是实现所需逻辑的每个事实:(a)迭代四个元素;(b) 每次迭代都包括从some_function()
获得成功的结果
你想要的语义确实是一个while
概念;已经有了这一内置功能
for i in range(1, 5):
while not some_function(i):
# Things you repeat until "some_function" succeeds
# Remainder of "for" loop
没有标准的方法,但是除了添加while
和continue
之外,我们可以使用all
功能:
n = 5
i = 1
while i < n:
if all(some_function(j) for j in range(i, n)):
i += 1
n=5
i=1
而i
为什么不想使用while循环?我想这是一条路here@Bernardostearnsreisen我可以用while循环模拟break/continue
,但我很高兴我不必这样做。据我所知,没有内置的方法可以做到这一点。是的,唯一肮脏的方法是在if子句中将I元素添加回迭代器。。。
n = 5
i = 1
while i < n:
if all(some_function(j) for j in range(i, n)):
i += 1