我如何将此代码转换为功能样式?

时间:2015-02-07 23:01:34

标签: python python-3.x

您如何建议我添加一个功能来缩短此代码并使其更有效?

这需要包括至少一个功能请帮助

import random


character1 = []
character2 = []
roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character1strength = x

roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character1skill = x

roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character2strength = x

roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character2skill = x

character1.append("strength")
character1.append(character1strength)
character1.append('skill')
character1.append(character1skill)

character2.append("strength")
character2.append(character2strength)
character2.append('skill')
character2.append(character2skill)

print(character1)
print(character2)

2 个答案:

答案 0 :(得分:2)

请注意,除以两个整数会让你失去精确度,所以不要这样做。

from random import randrange

def get_random_value():
    return randrange(1, 12, 1) / float(randrange(1, 4, 1))

def calculate_character():
    result = []
    for x in ('strength', 'skill'):
        result.extend([x, get_random_value()])
    return result

character1 = calculate_character()
character2 = calculate_character()

答案 1 :(得分:1)

您应该根据每个部分的功能(业务逻辑)重构和提取功能:

import random

def calc_rand():    
    roll12 = int(random.randrange(1, 12, 1))
    roll4 = int (random.randrange(1, 4, 1))
    return int(roll12 / roll4)

def fill_char(character):   
        character.append("strength")
        character.append(calc_rand())
        character.append('skill')
        character.append(calc_rand())

character1 = []
character2 = []
for character in [character1, character2]:
    fill_char(character)

print (character1)
print (character2)