我正在尝试生成 5 个唯一的随机数,并为它编写了一个 for 循环:
for i in range(5):
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
如果 x
不在 a
中,则只有 i
应该递增。我可以用 while 循环做到这一点,但想知道我们是否可以用 for 循环做到这一点。
答案 0 :(得分:1)
您可以通过将范围转换为列表来实现。 请按照给定的示例代码进行操作。
a = list()
n = 2
myrange = list(range(n)) # converting your range into list
for i in myrange:
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
else :
# add current i again in the rangelist at starting position
myrange.insert(0,i)
答案 1 :(得分:0)
您无法更改 for i in range()
循环运行的次数。在循环中更改 i
对 range()
对象没有影响。
您可以使用一个嵌套循环,不断询问,直到得到一个未找到的数字。
for _ in range(5):
while True:
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
break
答案 2 :(得分:0)
这里有一些方法:
选项 1:
在范围函数中使用无限值:
def to_infinity():
index = 0
while True:
yield index
index += 1
for i in to_infinity():
print("enter a no")
x = int(input())
if len(a) > 5:
break
if x not in a:
a.append(x)
选项 2:
使用 itertools.count:
import itertools
for i in itertools.count(start=1):
print("enter a no")
x = int(input())
if len(a) > 5:
break
if x not in a:
a.append(x)