【发布时间】:2013-07-07 20:10:47
【问题描述】:
我希望程序更高效,我正在考虑使用“for循环”,但我不知道如何在我的代码中实现它,而且写入文件的部分真的很长,我想让它更短
import random
def character_attributes():
initial_value = 10
character1_strength = initial_value + (random.randint(1,12) // random.randint(1,4))
character1_skill = initial_value + (random.randint(1,12) // random.randint(1,4))
character2_strength = initial_value + (random.randint(1,12) // random.randint(1,4))
character2_skill = initial_value + (random.randint(1,12) // random.randint(1,4))
print("Character 1 now has a strength attribute of {0}".format(character1_strength))
print("Character 1 now has a skill attribute of {0}".format(character1_skill))
print("Character 2 now has a strength attribute of {0}".format(character2_strength))
print("Character 2 now has a skill attribute of {0}".format (character2_skill))
myfile = open('character_attribute_data.txt', 'w')
myfile.writelines('Character 1 has a strength attribute of : ')
myfile.writelines(str(character1_strength))
myfile.writelines('\n')
myfile.writelines('Character 1 has a skill attribute of: ')
myfile.writelines(str(character1_skill))
myfile.writelines('\n')
myfile.writelines('Character 2 has a strength attribute of : ')
myfile.writelines(str(character2_strength))
myfile.writelines('\n')
myfile.writelines('Character 2 has a strength attribute of : ')
myfile.writelines(str(character2_skill))
myfile.close()
【问题讨论】:
-
请有人帮帮我:)
-
我建议为您的字符创建一个类,包括返回格式化字符串以打印属性输出的成员函数(可能通过重载
__repr__()),以及将此字符串转储到文件的另一种方法,最终使用with语句来完成此任务。但毕竟这与效率无关,也与 Python 3.x 无关。 -
对不起,我所说的效率是更少的代码行数
标签: python python-3.x