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

标签 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")

最佳答案

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

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")

关于python - 我有一段代码只适用于大于 1000 的数字。有解释为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28829086/

相关文章:

Python Pandas Lambda 行重命名匿名函数?

python - pandas 重新采样改变索引的数值

python - 使用 cython 并行化 python 循环 numpy.searchsorted

Python - 按元组值对元组键控字典进行排序

python - scipy-cluster 生成的树状图不显示

python - 如何计算与键关联的值的数量

python - 如何在 Sphinx 中避免 "SEVERE: Duplicate ID"警告我的 autodoc'd 模块?

python - 有没有办法在 django 中的静态资源末尾附加 etag

python - sqlite3 set_authorizer 方法出现问题

python - 使用 BeautifulSoup 或 minidom 解析 XML