【问题标题】:Generate list from user input从用户输入生成列表
【发布时间】:2016-12-18 20:48:05
【问题描述】:

我如何让用户输入类似Blah Blah [1-30] Blah 的内容,然后对其进行解析以获得这样的列表:

[
    'Blah Blah 1 Blah',
    'Blah Blah 2 Blah',
    etc...
    'Blah Blah 30 Blah',
]

【问题讨论】:

    标签: python regex list python-3.x python-3.4


    【解决方案1】:

    使用正则表达式。首先找到由[a-b]指定的起点和终点。然后循环它们,并将这些括号替换为递增的数字:

    import re
    expr = input('Enter expression: ') # Blah Blah [1-30] Blah
    start, end = map(int, re.findall('(\d+)-(\d+)', expr)[0])
    my_list = [re.sub('\[.*\]', str(i), expr) for i in range(start, end + 1)]
    
    >>> pprint(my_list)
    ['Blah Blah 1 Blah',
     'Blah Blah 2 Blah',
     ...
     'Blah Blah 29 Blah',
     'Blah Blah 30 Blah']
    

    【讨论】:

      【解决方案2】:

      如果您不想使用正则表达式,您可以尝试使用split

      user_input = input('Please enter your input e.g. blah blah [1-30] blah:')
      
      list_definiton = (user_input[user_input.find('[')+len(']'):user_input.rfind(']')])
      
      minimum = int(list_definiton.split('-')[0])
      maximum = int(list_definiton.split('-')[1])
      
      core_string = user_input.split('[' + list_definiton + ']')
      
      string_list = []
      for number in range(minimum, maximum + 1):
        string_list.append("%s%d%s" % (core_string[0], number, core_string[1]))
      
      print(string_list)
      

      试试here!

      【讨论】:

      • 它工作得很好,但正则表达式更短更清晰。不过感谢您的回答。
      【解决方案3】:

      根据您的需要进行编辑:

      import re
      seqre = re.compile("\[(\d+)-(\d+)\]")
      s = "Blah Blah [1-30] blah"
      
      seq = re.findall(seqre, s)[0]
      start, end = int(seq[0]), int(seq[1])
      
      l = []
      for i in range(start, end+1):
          l.append(re.sub(seqre, str(i), s))
      

      【讨论】:

      • 这是在 python 3 中:P 但我希望用户输入一行然后程序生成列表。
      • 行会有特定的分隔符吗?例如逗号?
      • 我可以做 input().split(', ') 但问题在于用户必须输入 j1、j2、j3 等...而不是 j[1 -10]
      • 新答案不起作用。关于你如何开始的事情——[135,136] 返回 [5,6,7,8,...,136]
      猜你喜欢
      • 2013-05-09
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多