【问题标题】:Python: Finding strings in a list containing an interval and replacing this interval by every number in itPython:在包含区间的列表中查找字符串,并用其中的每个数字替换该区间
【发布时间】:2026-02-14 00:35:01
【问题描述】:

我想知道是否有任何漂亮/干净的方式来做我想做的事情:)。 (我确定有) 所以我的函数接收一个字符串列表,可以包含两种格式的字符串: “12,13,14,15”或“12 到 15” 目标是解析第二种类型并将“to”替换为区间中的数字。

数字之间的分隔符无关紧要,正则表达式将在之后完成这项工作。 这是伪代码和丑陋的实现

这个想法是用区间中的数字替换列表中的“to”,以便之后我可以使用正则表达式轻松解析数字

# The list is really inconsistent, separators may change and it's hand filled so some comments like in the last example might be present
l = ["12,13,14,15",
     "12 to 18",
     "10,21,22 to 42",
     "14,48,52",
     "12,14,22;45 and also 24 to 32"
]

def process_list(l):
  for x in l:
     if "to" in x:
         # Find the 2 numbers around the to and replace the "to" by ",".join(list([interval of number]))
  final_list = numero_regex.findall(num)
  return final_list

【问题讨论】:

    标签: python pandas list


    【解决方案1】:

    这是一种解决方案:

    from itertools import chain
    def split(s):
        return list(chain(*(list(range(*list(map(int, x.split(' to ')))))+[int(x.split(' to ')[1])]
                            if ' to ' in x else
                            [int(x)]
                            for x in s.split(',')
                           )))
        
    [split(e) for e in l]
    

    输出:

    [[12, 13, 14, 15],
     [12, 13, 14, 15, 16, 17, 18],
     [10, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42],
     [14, 48, 52]]
    

    编辑:我将上述解决方案改编为与正则表达式一起使用:

    from itertools import chain
    def split(s):
        regex = re.compile('(\d+\s*to\s*\d+|\d+)')
        return list(chain(*([int(x)] if x.isnumeric() else 
                            list(range(*map(int, re.split('\s+to\s+', x))))
                            +[int(re.split('\s+to\s+', x)[-1])]
                            for x in regex.findall(s)
                           )))
    

    【讨论】:

    • 很好的答案我真的很喜欢。我将使用正则表达式的原因是列表非常混乱。一些元素可能是这样的: ["12,21,32;14, and the 12 to 40"] 分隔符不一致,所以我想要这样的输出 ["12,21,32;14, and the 12 ,13,14,15,[...],40"]。我可以很容易地用正则表达式解析——
    • @JulesSpender 请注意,您可以使用re.split 将其与正则表达式结合使用;)例如re.split('[,;]')
    • @JulesSpender 我更新了答案
    【解决方案2】:

    我认为你不需要正则表达式:

    def process_list(l):
        final_list = []
        for s in l:
            l2 = []
            for n in s.split(','):
                params = n.split(' to ')
                nums = list(range(int(params[0]), int(params[-1])+1))
                l2.extend(nums)
            final_list.append(l2)
        return final_list
    

    输出:

    >>> process_list(l)
    
    [[12, 13, 14, 15],
     [12, 13, 14, 15, 16, 17, 18],
     [10, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42],
     [14, 48, 52]]
    
    

    更新

    我想要这样的输出 ["12,21,32;14, and the 12,13,14,15,[...],40"]。我可以很容易地用正则表达式解析

    如果你只是想替换'number1 to number2',你可以这样做:

    def process_list(l):
        def to_range(m):
            return ','.join([str(i) for i in range(int(m.group('start')),
                                                   int(m.group('stop'))+1)])
        return [re.sub(pat, to_range, s) for s in l]
    

    输出:

    # l = ["12,21,18 to 20;32;14, and the 12 to 16"]
    >>> process_list(l)
    ['12,21,18,19,20;32;14, and the 12,13,14,15,16']
    

    【讨论】:

    • 很好的答案我真的很喜欢。我将使用正则表达式的原因是列表非常混乱。一些元素可能是这样的: ["12,21,32;14, and the 12 to 40"] 分隔符不一致,所以我想要这样的输出 ["12,21,32;14, and the 12"] ,13,14,15,[...],40"]。我可以很容易地用正则表达式解析
    • 太漂亮了!感谢您的帮助!
    最近更新 更多