有没有办法让这个程序更有效率?

时间:2013-07-07 20:10:47

标签: python python-3.x

我希望程序更有效率,我想使用'for循环'但我不知道如何在我的代码中实现它,而且写入文件部分真的很长我想让它缩短< / p>

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

2 个答案:

答案 0 :(得分:2)

我认为从更高的速度来看,你可以获得更高的效率。你正在使用python函数进行所有的字符串操作,你在python中几乎没有任何好处。

但是你的代码在开发速度方面效率不高。想象一下,你想用'Person'改变'Character'然后你必须改变8行代码。 unutbu的答案例如为你提供了一个更好的解决方案的提示,甚至可以通过引入moooeeeep指出的字符类来改进。即使您现在认为这是纯粹的化妆品,从长远来看,它将帮助您提高性能,因为您将能够进行更改(例如,您找到的优化)与当前不可维护的代码形成对比。

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

编辑: 对不起,我的意思是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逻辑更容易

答案 1 :(得分: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')