使用随机数确定随机数列表的长度

时间:2015-11-21 22:18:30

标签: python random

我试图生成一个特定范围内的随机奇数列表,其中列表的长度是通过在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()

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

您必须检查rand_output % 2 != 0是否n % 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()