【问题标题】:Take a List and an integer as input from user将列表和整数作为用户的输入
【发布时间】:2022-01-04 10:39:40
【问题描述】:

我想将列表和一个整数作为用户的输入。 我尝试通过以下方式使用拆分方法:

lst,n=input().split(",")
print(lst)
print(n)

输入:

[1,2,3,4],5

预期输出:

[1,2,3,4]
5

【问题讨论】:

  • 用这个作为你的列表输入lst = list(map(int, input("Enter the values with , between them: ").split(",")))

标签: python list input split integer


【解决方案1】:

您可以匹配 [...] 或使用带有交替的模式匹配 1 个或多个数字

import re

pattern = r"\[[^][]*\]|\d+"
s = "[1,2,3,4],5"
print(re.findall(pattern, s))

输出

['[1,2,3,4]', '5']

或者更精确一点,只匹配可选的用逗号、空格和更多数字分隔的数字:

\[\s*\d+(?:\s*,\s*\d+)*\s*]|\d+

【讨论】:

    【解决方案2】:

    如果你只是省略括号并使用扩展的可迭代解包会更容易。

    *lst, n = map(int, input().split(','))
    

    这将为您提供lst = [1, 2, 3, 4]n = 5 作为输入1,2,3,4,5

    注意/警告:1 的输入将为您提供 lst = []n = 1

    【讨论】:

      【解决方案3】:

      为了能够编写lst,n = ...,您只需将输入拆分一次,在最后一个逗号上。因此,您应该使用str.rsplit(maxsplit=1),而不是str.split

      那么,由于列表被[] 字符包围,您需要在拆分列表之前丢弃这些字符。

      最后,由于输入由字符组成,但您需要数字,您应该调用int 将字符串转换为数字。

      def list_and_number(s):
          s,n = s.rsplit(',', maxsplit=1)
          n = int(n)
          lst = [int(x) for x in s.strip('[]').split(',')]
          return lst, n
      
      lst, n = list_and_number(input())
      print(lst)
      print(n)
      
      # INPUT
      [1,2,3,4],5
      
      # OUTPUT
      [1, 2, 3, 4]
      5
      
      

      【讨论】:

      • 我被限制使用 python 3.8 并且 removeprefix 和 removesuffix 在 3.8 上不起作用
      • @ShreyashKashid 我已将.removeprefix('[').removesuffix(']') 替换为.strip('[]')
      【解决方案4】:

      如果你想为程序提供外部输入,你可以将其定义为 sys.argv

      import sys
      
      print("Give me the list")
      lst = sys.argv[0]
      print("Give me the number")
      num = sys.argv[1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-19
        • 2017-10-07
        • 1970-01-01
        • 2022-01-24
        • 2015-07-04
        • 2018-08-15
        相关资源
        最近更新 更多