我不知道如何向這段代碼添加額外的條件。(僅使用randint)
例如對于串列 [1, 2, 3, 4, 0] 我需要生成除最后一個之外的亂數(在我的代碼中覆寫)但下一個條件是,它不能選擇值為 0 的索引號. 所以對于串列 [3, 3, 0, 3, 3, 7] 它只能考慮索引 0,1,3,4 (不是 2 和 5,因為我不能包括最后一個數字和值為 0 的索引)。
到目前為止我的代碼:
import random
our = [2, 3, 4, 0]
random_index = random.randint(0, len(our)-2)
random_number = our[random_index]
print(random_number)
我會很高興得到任何幫助。
uj5u.com熱心網友回復:
您可以創建存盤有效索引值的第二個串列。
import random
our = [3, 3, 0, 3, 3, 7]
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
# index: [0, 1, 3, 4]
random_index = random.choice(index)
編輯:您可以對存在的非零值執行健全性檢查。
如果可迭代物件的任何元素為 ,則該any()函式回傳。被視為并且所有非零數字都是。TrueTrue0FalseTrue
valid_index = any(our[:-1])
if valid_index:
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
uj5u.com熱心網友回復:
您可以使用 while 回圈來檢查數字是否等于 0。
import random
our = [3, 6, 2, 0, 3, 0, 5]
random_number = 0
while random_number == 0:
random_index = random.randint(0, len(our)-2)
random_number = our[random_index]
print(random_number)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316352.html
下一篇:Python常用庫的使用(Numpy,Pandas,Matplotlib,wordcloud,Opencv-python,PIL)
