2016-11-24 71 views
-1

我想用隨機的順序編號1-24的數字,爲什麼這不起作用?如何在不重複的情況下將數字輸入到列表中?

full_list = [] 

x = 0 
while x < 25 : 
    n = randint (1,24) 
    while n in full_list: 
     n = randint (1,24) 
    full_list.append(n) 
    x = x + 1 
+0

檢查新號碼是否已經在列表中。丟棄,如果是,並再次選擇 –

+4

或更簡單的使用shuffle - 請參閱:http://stackoverflow.com/questions/976882/shuffling-a-list-of-objects-in-python –

+1

你想要的東西像'shuffle (範圍(1,25))' –

回答

7

隨機有shuffle功能將更有意義,這個任務:

ar = list(range(1,25)) 
random.shuffle(ar) 
ar 
> [20, 14, 2, 11, 15, 10, 3, 4, 16, 23, 13, 19, 5, 21, 8, 7, 17, 9, 6, 12, 22, 18, 1, 24] 

而且,你的解決方案不起作用,因爲while x < 25需求是while x < 24。當x = 24(因爲randint(1,24)永遠不會生成一個不在列表中的新數字)時,它處於無限循環。

相關問題