我有一段代码,只适用于大于1000的数字。有什么解释吗?

2024-04-25 02:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用这段代码为我正在做的一个项目随机取学生的名字和成绩,但是当我只想取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")

Tags: ofthetoinfromforcreaterandom
1条回答
网友
1楼 · 发布于 2024-04-25 02:28:29

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

file.close()

(如果您正在repl或ipython中运行,则在退出之前,文件可能不会“关闭自身”。)

但是你的代码中还有很多其他非常非Pythonic的方面,我现在没有时间去看了!。。。简短示例:

  • 不要使用“文件”作为名称,因为它已经是内置的。你知道吗
  • 不要费心做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")

相关问题 更多 >