我試圖讓函式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
uj5u.com熱心網友回復:
你用嵌套串列呼叫函式,不要這樣做
if check([tmp]) == True:
應該只是
if check(tmp):
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439258.html
上一篇:比較串列中的元素
下一篇:python中的串列連接中的串列
