【问题标题】:is there any way of making this program more efficient?有没有办法让这个程序更有效率?
【发布时间】: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


【解决方案1】:

我不认为你可以从更高的速度的意义上获得更高的效率。你正在使用 python 函数来处理所有的字符串,而且你在 python 中几乎不会变得更好。

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

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

编辑: 对不起,我的意思是对这个问题发表评论: 这是一个从 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 类添加复杂逻辑

【讨论】:

  • 您能否为 moooeeeep 添加相关链接和/或您提到的可能对 OP 有帮助的类的简短原型?谢谢!
【解决方案2】:

这并没有使代码更高效,但确实使它更短:

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

【讨论】:

  • 对不起我没看懂那段代码很好我只是一个初学者
猜你喜欢
  • 2019-12-11
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 2015-08-13
  • 2011-06-28
  • 2021-02-01
  • 2014-12-11
  • 2013-11-15
相关资源
最近更新 更多