代码之家  ›  专栏  ›  技术社区  ›  Dakota Brown

将基数转换为2到9之间的基数

  •  -1
  • Dakota Brown  · 技术社区  · 7 年前

    好吧,我迷路了,一直在思考如何取得进一步的进展。 该程序将用户输入基数的值返回到如下列表[1,2,2]。 我试着做两件事。首先,不是像这样的单个数字

    userInt = 50
    

    我希望能够输入

    userList = [50, 3, 6, 44]
    

    然后让公式将每个数字转换为正确的基数。

    因此,如果我将其转换为基数6,我希望结果是:

    userNewList = [122, 3, 10, 112]
    

    我用for循环尝试过这个方法,但无法正确执行,结果只是通过了一个int is not iterable类型错误。

    def baseConversion(userInt, base):
        remList = []
        while(userInt > 0):
            remList.append(userInt % base)
            userInt = userInt // base     
        return (remList[::-1])       
    
    
    def main():
        base = int(input('Enter a base: '))
        userInt = 50
        remList = baseConversion(userInt, base)
        baseConversion(userInt, base)
        print(remList)
    main()
    

    我感谢你能提供的任何帮助。

    1 回复  |  直到 7 年前
        1
  •  1
  •   mshsayem    7 年前

    使用Python 2.7,但您可以理解:

    >>> def baseConversion(userInt, base):
            remList = ''
            while(userInt > 0):
                remList += str(userInt % base)
                userInt = userInt // base
            return int(remList[::-1]) # If you are just printing, you don't need to convert to int.
    
    >>> def main():
            base = int(raw_input('Enter a base:'))
            userInt = [int(s.strip()) for s in raw_input('Enter numbers (comma separated):').split(',')]
            result = [baseConversion(i, base)  for i in userInt]
            print result
    
    
    >>> main()
    Enter a base:6
    Enter numbers (comma separated):50,3,6,44
    [122, 3, 10, 112]