【问题标题】:Integer list python整数列表python
【发布时间】:2014-01-27 20:23:55
【问题描述】:

我遇到了这个列表的问题,我想将每个数字乘以某个数字,但目前列表中的每个数据都是一个字符串,如果我将列表转换为整数或将字符串转换为一个整数并将其放入一个列表中,我得到一个错误。

def main():
    isbn = input("Enter you're 10 digit ISBN number: ")
    if len(isbn) == 10 and isbn.isdigit():
        list_isbn = list(isbn)
        print (list_isbn)
        print (list_isbn[0] * 2)
    else:
        print("Error, 10 digit number was not inputted and/or letters were inputted.")
        main()


if __name__ == "__main__":
    main()
    input("Press enter to exit: ")

【问题讨论】:

  • 你没有数组,你有一个列表; Python 有很大的不同。
  • 您遇到什么错误?你期望的输出是什么?
  • 我不知道这是否是您需要的,但更改第 3 行并通过以下代码使代码编译。 if len(str(isbn)) == 10 and str(isbn).isdigit():list_isbn = str(isbn)
  • @sk4x0r:这是 Python 3,我想说,input() 返回一个 string

标签: python string list integer


【解决方案1】:

你可以将每个单独的字符变成一个整数:

list_isbn = [int(c) for c in isbn]

演示:

>>> isbn = '9872037632'
>>> [int(c) for c in isbn]
[9, 8, 7, 2, 0, 3, 7, 6, 3, 2]

【讨论】:

    【解决方案2】:

    @Martijn Pieters 答案将不起作用,因为输入已经将项目读取为整数,并且在他的示例中,他将 ISBN 定义为字符串。 --

    问题在于 len 内置函数用于序列(管件、列表、字符串)或映射(字典),而 isbn 是一个 int。

    isdigit 也是如此。

    我在下面发布了一个工作程序:

    def main():
        # number to multple by
        digit = 2
        isbn = input("Enter you're 10 digit ISBN number: ")
        # Liste generator that turns each the string from input into a list of ints
        isbn = [int(c) for c in str(isbn)]
    
        # this if statement checks to make sure the list has 10 items, and they are
        # all int's
        if len(isbn) == 10 and all(isinstance(item, int) for item in isbn):
            # another list generator that multiples the isbn list by digit
            multiplied = [item * digit for item in isbn]
            print multiplied
        else:
            print("Error, 10 digit number was not inputted and/or letters were inputted.")
            main()
    
    
    if __name__ == "__main__":
        main()
        input("Press enter to exit: ")
    

    【讨论】:

      【解决方案3】:

      改变这一行

      isbn = input("Enter you're 10 digit ISBN number: ")
      

      isbn = raw_input("Enter you're 10 digit ISBN number: ")
      

      【讨论】:

        猜你喜欢
        • 2010-12-26
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多