0

我希望程序更高效,我正在考虑使用“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()
4

2 回答 2

2

我认为从更高的速度的意义上说,您无法获得更高的效率。您正在使用 python 函数进行所有字符串操作,并且在 python 中您几乎不会变得更好。

但是您的代码在开发速度方面效率不高。想象一下,您想通过“人”更改“字符”,那么您必须更改 8 行代码。例如,unutbu 的答案为您提供了一个更好的解决方案的提示,甚至可以通过引入 moooeeeeep 指出的字符类来改进这一点。即使您现在认为这是纯粹的装饰,但从长远来看,它会帮助您提高性能,因为您将能够对当前不可维护的代码进行更改(例如,您发现的优化)。

另一点是,我很难相信你真的会遇到这段代码的性能问题。它只是将几行写入单个文件中。小心不要优化你不需要的东西(过早的优化)。只有当您遇到性能问题时,才分析瓶颈并尝试改善最坏的情况。

编辑:对不起,我的意思是 moooeeeep 对这个问题的评论:这是一个原型,它从 unutbu 扩展了示例,其中包含一个包含属性信息的类:

import random

class Character(object):
    '''
    This class holds all the information concerning a character, it's attributes, 
    the character number, ...
    '''
    def __init__(self, character_number, initial_value):
        '''
        Initialize a new character object with character_number and initial_value
        '''
        self.strength = initial_value + (random.randint(1,12) // random.randint(1,4))
        self.skill = initial_value + (random.randint(1,12) // random.randint(1,4))
        self.character_number = character_number

    def get_attributes_dict(self):
        '''
        return a dictionary with the attributes names and their values for this character
        '''
        return {'strength': self.strength,
                'skill': self.skill
                }


def writeout_character_attributes(characters_list):
    '''
    this function writes a complete list of character into a file
    '''
    #The 'with' statement is used here, because it automatically closes the 
    #file at the end of this block, so you cannot forget it 
    with open('character_attribute_data.txt', 'w') as myfile:
        #iterate over the character in the list
        for character in characters_list:
            #get all the attributes for the current character
            attributes = character.get_attributes_dict()
            #iterate over the attributes names and values, 
            #defined in the character class
            for attribute_name, val in attributes.items():
                msg = "Character {i} now has a {attribute_name} attribute of {val}".format(
                    i= character.character_number, attribute_name=attribute_name, val=val)
                print(msg)
                myfile.write(msg+'\n')


def get_list_of_characters(initial_value):
    list_of_characters = []
    # we want two characters with numbers 1 and 2
    for i in range(1, 3):
        #create a new character
        character = Character(i, initial_value)
        #add this character to the list of characters
        list_of_characters.append(character)
    return list_of_characters

if __name__ == '__main__':
    list_of_characters =  get_list_of_characters(10)
    writeout_character_attributes(list_of_characters)

它可能不是更少的代码行,但它更容易,例如添加更多属性或向 Character 类添加 komplex 逻辑

于 2013-07-07T21:48:27.777 回答
0

这不会使代码更高效,但它确实使它更短:

import random

def random_val(initial_value):
    return  initial_value + (random.randint(1,12) // random.randint(1,4))

def character_attributes():
    initial_value = 10
    with open('character_attribute_data.txt', 'w') as myfile:
        for i in range(1, 3):
            attributes = {
                'strength': random_val(initial_value)
                'skill': random_val(initial_value)}
            for key, val in attributes.items():
                msg = "Character {i} now has a {key} attribute of {val}".format(
                    i=i, key=key, val=val)
                print(msg)
                myfile.write(msg+'\n')
于 2013-07-07T20:58:27.557 回答