我有一段代码,它只适用于大于1000的数字.任何原因的解释



我一直在使用这段代码为我正在进行的项目随机生成学生的名字和成绩,但当我只想生成100个名字而不是1000个名字时,我写入的文本文件就不会发生任何变化。

from random import randint
file = open("rawgrade.txt", "w")
# Create the list of all the letters in the alphabet to easily select from
alphalist = []
for letter in "abcdefghijklmnopqrstuvwxyz":
    alphalist.append(letter)
# Create random people and grades for the test file
for i in range(100): # only works for 1000 and up in my trials  
    # Create the random name of the person
    namelen = randint(1, 16)
    namestr = ""
    for j in range(namelen):
        randomletter = randint(0,25)
        namestr += alphalist[randomletter]
    # Create the random grade for the person
    grade = randint(0, 100)
    # Write to file
    file.write(namestr + " " + str(grade) + "n")

完成后需要关闭文件。否则,结果是不可预测的:

file.close()

(如果你在repl或ipython中运行,那么在你退出之前,文件可能不会"自行关闭"。)

但是你的代码还有很多其他非常非Python的方面,我现在没有时间复习!。。。短样本:

  • 不要使用"file"作为名称,因为它已经是内置的
  • 不要麻烦制作alphalist,因为您可以对字符串进行索引
  • 使用with打开和关闭

为了好玩,下面是我认为更好的版本:

from random import randint, choice
from string import ascii_lowercase
num_students = 100
max_name_len = 16
with open("rawgrade.txt", "w") as fil:
    # Create random people and grades for the test file
    for i in range(num_students):  
        # Create the random name of the person
        ### this can probably be made simpler....
        namelen = randint(1, max_name_len)
        namestr = ''.join([choice(ascii_lowercase) for j in range(namelen)])
        # Create the random grade for the person
        grade = randint(0, 100)
        # Write to file
        fil.write(namestr + " " + str(grade) + "n")

相关内容

最新更新