如何重构这个 for 循环以遵守 DRY 原则?

How can I refactor this for loop to adhere to the DRY principle?

如何在不重复注释行的情况下保留下面代码的功能?

def my_round(number, place=10):
    digit_list = [digit for digit in str(number)]
    rounded_number = ''
    round_list = [10 ** i for i in range(10)]
    zeros = str(place).count('0')

    for i in round_list:
        if (place == i):
            if int(digit_list[-zeros]) >= 5:
                for x in range(-zeros, 0):                # <- These 
                    digit_list[x] = '0'                   # <-
                rounded_number = int(''.join(digit_list)) # <-
                rounded_number += i
            else:
                for x in range(-zeros, 0):                # <- Repeat...
                    digit_list[x] = '0'                   # <-
                rounded_number = int(''.join(digit_list)) # <-

    return rounded_number

print(my_round(56, 10))

我是 Python 和一般编程的新手。这也是我在 Whosebug 上的第一个问题,但请不要犹豫告诉我在 Python!

中提问或编码方面我可以在哪里做得更好

我好学!

去除重复的一般方法是定义一个函数。这甚至可以在另一个函数中完成:

def my_round(number, place=10):
    digit_list = [digit for digit in str(number)]
    rounded_number = ''
    round_list = [10 ** i for i in range(10)]
    zeros = str(place).count('0')

    def round_inner():
        for x in range(-zeros, 0):
            digit_list[x] = '0'
        return int(''.join(digit_list))

    for i in round_list:
        if (place == i):
            if int(digit_list[-zeros]) >= 5:
                rounded_number = round_inner()
                rounded_number += i
            else:
                rounded_number = round_inner()

    return rounded_number

对于你的情况,有一个更简单的方法:

def my_round(number, place=10):
    digit_list = [digit for digit in str(number)]
    rounded_number = ''
    round_list = [10 ** i for i in range(10)]
    zeros = str(place).count('0')

    for i in round_list:
        if (place == i):
            round_up = int(digit_list[-zeros]) >= 5
            for x in range(-zeros, 0):
                digit_list[x] = '0'
            rounded_number = int(''.join(digit_list))

            if round_up:
                rounded_number += i

    return rounded_number

不确定您的示例是否故意令人费解,但如果不是,您可以将其全部替换为:

def my_round(number, place=10):
    return int(round(float(number) / place) * place)