将八进制数转换为十进制数的算法?

Algorithm for converting octal numbers to decimal?

我有一个要转换为十进制的八进制数列表。这是我的 class 以及我到目前为止所做的事情:

class Octal:

    #Reads in the file into numberList, converting each line into an int.
    def __init__(self):
        list = []
        file = open("Number Lists/random_numbers3.txt")
        for line in file:
            list.append(int(line))
        self.numberList = list
        file.close()

    #Convert numberList to decimal
    def dec_convert(self):
        decimal = 0
        decimalList = []
        for line in self.numberList:
            temp = str(line)
            i = 0
            while i < len(temp):
                digit = int(temp[i])
                item = (digit * (8 ** (len(temp) - i)))
                decimal = decimal + item
                i += 1

            decimalList.append(decimal)
        return decimalList



    def get_list(self):
        return self.numberList

我从文件中读入了数字,效果很好。但我认为我的 dec_convert() 函数实际上不起作用。它只是保持 运行 而没有完成。

它看起来非常糟糕并且难以阅读,所以我想知道是否有更简单的方法将列表中的每个八进制数转换为十进制数?

是的,您可以使用 列表理解:

def dec_convert(self):
    decimalList = [self._convert_to_dec(line) for line in self.numberList]

并与:

def _convert_to_dec(self,dec) :
    n = len(temp)-1
    return sum(int(x)*(8**(n-i)) for i,x in enumerate(dec))

第一个代码片段是一个简单的列表理解,它在 `self.numberList 中的 所有元素上调用 self._convert_to_dec。那里没有多少魔法。

_convert_to_dec比较复杂:我们先计算位数,存入n。接下来我们定义一个生成器,它 enumerate 遍历字符并将 i 绑定到相应的索引。生成器将每个元素乘以相应的 8 和数字的幂。这是一个生成器,所以没有构建真正的列表。

通过运行 this through sum 我们得到请求结果的总和。

或者作为 says, you can use int 给定的碱基(在本例中 8.

这是一个简单的解决方案,它使用内置 int() 构造函数而不是您的 dec_convert() 函数。

class Octal:
    def __init__(self):
        with open("Number Lists/random_numbers3.txt") as fp:
            self.numberList = map(lambda x:int(x,8), fp)
    def get_list(self):
        return self.numberList

if __name__=="__main__":
    o = Octal()
    print(o.get_list())