【问题标题】:Taking a list as input from user将列表作为用户的输入
【发布时间】:2020-06-02 16:41:40
【问题描述】:

在将列表作为用户的输入时,输入应该用方括号括起来,而不是仅仅输入数字 这是我从用户那里获取多个输入以获取列表的代码

a = list(map(int,input().strip().split(', ')))

默认输入为 [1, 2, 3, 4]。 当我运行我的代码时,我得到一个错误:

ValueError: invalid literal for int() with base 10: '[1'

我知道它发生的原因是因为 '[1' 是一个不能转换为 int 的元素,它(方括号和 1)被视为索引 0 处的列表的第一个元素。 拥有方括号对我来说绝对必要,我该如何解决错误或忽略方括号?是否有可能有效的忽略方法或类似方法? 干杯!

【问题讨论】:

    标签: python list split


    【解决方案1】:

    从输入中去掉括号:

    a = [int(n) for n in input().strip('[]').split(',')]
    

    【讨论】:

      【解决方案2】:

      您可以通过简单的方式使用 strip() 删除多余的空格和 '[ ]'。

      a = list(map(int, input().strip(' []').split(',')))
      

      【讨论】:

        【解决方案3】:

        您可以在将其转换为 int 之前将其从字符串中删除:

        a = list(map(int,
                     input()
                     .strip()
                     .replace('[', '')
                     .replace(']', '')
                     .split(', ')
                    )
                )
        

        或者您也可以使用正则表达式来获取所有数字:

        import re
        a = list(map(int, re.findall(r'\d+', input())))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-27
          • 1970-01-01
          相关资源
          最近更新 更多