【问题标题】:How to parse comma-separated integers from user input [duplicate]如何从用户输入中解析逗号分隔的整数[重复]
【发布时间】:2020-11-01 16:10:14
【问题描述】:

我想接受由几个逗号分隔的整数组成的用户输入并将它们放在一个列表中。这些值用逗号分隔。假设我将100,97,84 作为输入,所需的输出将是[100, 97, 84]。我正在尝试以下代码:

int(input("Please enter the numbers: "))

但它给了我:

ValueError: invalid literal for int() with base 10: '100,97,84'

我该怎么办?

【问题讨论】:

    标签: python io


    【解决方案1】:

    由于您的短语包含逗号,请将其放在引号中以将其转换为具有以下短语的整数:

    s = (input("Enter the numbers :"))
    result = ''.join([i for i in s if  i.isdigit()])
    print(result)
    

    例子

    Enter the numbers :12,34
    

    输出:

    1234
    

    错误问题将得到解决

    【讨论】:

    • 不,OP 想要输入三个不同的整数,而不是一个大整数。
    • 我觉得数字是用123456的形式输入的,就是用上面的代码转换成数字的数字和逗号的组合。
    【解决方案2】:

    如果你想写用逗号分隔的数字,首先你必须把你的输入分成一个只有数字的字符串列表,然后通过 int 映射这个列表:

    numbers = [int(s) for s in input("Please enter numbers separated by a comma:").split(',')]
    

    【讨论】:

      【解决方案3】:

      input 将始终返回一个字符串,即使它是一个数字

      如果你想要一个数字,你写int(input"Enter number :))

      我不知道您的输出和输入之间的关系是什么,但是您希望输入 list 作为 input。你可以这样做

      s = (input("Enter the numbers :"))
      numbers = list(map(int, s.split()))
      

      这将返回numbers 中的列表。您输入的数字之间带有space,而不是comma

      例如

      Enter the numbers :100 97 84
      Ouput>>>[100, 97, 84]
      

      如果您希望它们不带括号并用逗号分隔,您可以使用 print(*numbers, sep=',') 会给

      Enter the numbers :100 97 84
      Output>>>100,97,84
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 2020-12-06
        • 1970-01-01
        相关资源
        最近更新 更多