如果满足条件,则将随机整数添加到列表中
Adding random integers to list if criteria met
我正在尝试让函数 make(ls)
生成一个包含 4 个随机整数的列表。如果这些整数通过函数 check(ls)
中的三个检查,它们应该作为列表添加到 res.如果他们没有通过,将生成另一组,直到我有一个包含 4 个列表的列表。下面的代码给了我 IndexError: list index out of range
- 有什么想法吗?
def check(ls):
for n in ls:
if n==0 or ls[0] == ls[2] or ls[1] == ls[3]:
return False
return True
def make(ls):
res = []
while len(res) < 4:
tmp = [randint(1,9),randint(1,9),randint(1,9),randint(1,9)]
if check([tmp]) == True:
res.append(tmp)
return res
你用嵌套列表调用函数,不要这样做
if check([tmp]) == True:
应该只是
if check(tmp):
我正在尝试让函数 make(ls)
生成一个包含 4 个随机整数的列表。如果这些整数通过函数 check(ls)
中的三个检查,它们应该作为列表添加到 res.如果他们没有通过,将生成另一组,直到我有一个包含 4 个列表的列表。下面的代码给了我 IndexError: list index out of range
- 有什么想法吗?
def check(ls):
for n in ls:
if n==0 or ls[0] == ls[2] or ls[1] == ls[3]:
return False
return True
def make(ls):
res = []
while len(res) < 4:
tmp = [randint(1,9),randint(1,9),randint(1,9),randint(1,9)]
if check([tmp]) == True:
res.append(tmp)
return res
你用嵌套列表调用函数,不要这样做
if check([tmp]) == True:
应该只是
if check(tmp):