2015-11-21 73 views
0

我想通過調用PYTHON中的另一個隨機數生成的列表的長度生成一個特定範圍內的隨機奇數列表(然後寫入它們到一個文件)。使用隨機數來確定一個隨機數列表的長度

我已經能夠生成最初的隨機數(並扔在顯示調用者看它是什麼)。當我嘗試使用它作爲另一個隨機生成的數字列表的長度時,它不起作用。我不確定爲什麼。任何洞察力將不勝感激。下面是我得到了什麼?

import random 

def main(): 
    digit_file = open("numbers.txt","w") 
    file_size = random.randint(4,7) 
    print (file_size) 
    print ("is the file size\n") 
    for n in range(file_size): 
     rand_output = random.randint(5,19) 
     if n %2 != 0: 
      print(rand_output) 
      digit_file.write(str(rand_output)) 
    digit_file.close 
    print("File was created and closed.") 
main() 
+0

這是什麼問題?代碼起作用。另外不要忘記在'digit_file.close()'中使用圓括號' – pythad

+0

@FadingCaptain你怎麼知道它不起作用? –

+0

rand_output生成的數字量不等於file_size。 –

回答

0

你必須檢查是否rand_output % 2 != 0n % 2 != 0

import random 


def main(): 
    digit_file = open("numbers.txt", "w") 
    file_size = random.randint(4, 7) 
    print(file_size) 
    print("is the file size\n") 
    while file_size: 
     rand_output = random.randint(5, 19) 
     if rand_output % 2 != 0: 
      print(rand_output) 
      digit_file.write(str(rand_output)) 
      file_size -= 1 
    digit_file.close() 
    print("File was created and closed.") 
main() 
+0

我試過了,但生成的file_size數字是7,rand_output生成的數字位數是5. –

+0

@FadingCaptain,我第一次理解你錯了。我已經更新了我的回答 – pythad

+0

輝煌!我是編程新手,並不記得使rand_output依賴於file_size。爲什麼最後需要從file_size中減去1? –

1

不是一定要了解你所期望的,但是關於使用choice什麼?

from random import randint,choice 

def main(): 
    with open("numbers.txt","w") as digit_file: 
     file_size = randint(4,7) 
     print (file_size) 
     print ("is the file size\n") 
     for n in range(file_size): 
      rand_output = choice(range(5, 19, 2)) 
      print(rand_output) 
      digit_file.write(str(rand_output)) 
    print("File was created and closed.") 

main() 

,可以成爲:

from random import randint,choice 

def main(): 
    with open("numbers.txt","w") as f: 
     file_size = randint(4,7) 
     print ("%dis the file size\n" % file_size) 
     f.write(''.join(str(choice(range(5, 19, 2))) for _ in range(file_size))) 
    print("File was created and closed.") 

main()