【问题标题】:Append two integers to list when seperated by '..' Python当用'..' Python 分隔时,将两个整数附加到列表中
【发布时间】:2012-09-15 10:16:55
【问题描述】:

如果我有一个列表字符串:

first = []
last = []

my_list = ['  abc   1..23',' bcd    34..405','cda        407..4032']

我如何将 .. 两侧的数字附加到相应的列表中?得到:

first = [1,34,407]
last = [23,405,4032]

我也不介意字符串,因为我可以稍后转换为 int

first = ['1','34','407']
last = ['23','405','4032']

【问题讨论】:

    标签: python string list integer find


    【解决方案1】:

    使用re.search 匹配.. 之间的数字并将它们存储在两个不同的组中:

    import re
    
    first = []
    last = []
    
    for s in my_list:
      match = re.search(r'(\d+)\.\.(\d+)', s)
      first.append(match.group(1))
      last.append(match.group(2))
    

    DEMO.

    【讨论】:

    【解决方案2】:

    我会使用正则表达式:

    import re
    num_range = re.compile(r'(\d+)\.\.(\d+)')
    
    first = []
    last = []
    
    my_list = ['  abc   1..23',' bcd    34..405','cda        407..4032']
    
    for entry in my_list:
        match = num_range.search(entry)
        if match is not None:
            f, l = match.groups()
            first.append(int(f))
            last.append(int(l))
    

    这会输出整数:

    >>> first
    [1, 34, 407]
    >>> last
    [23, 405, 4032]
    

    【讨论】:

      【解决方案3】:

      另一种解决方案。

      for string in my_list:
          numbers = string.split(" ")[-1]
          first_num, last_num = numbers.split("..")
          first.append(first_num)
          last.append(last_num)
      

      如果 my_list 中有一个没有空格的字符串,或者某些字符串的最后一个空格后没有“..”(或者最后一个空格后有多个“..”,它将抛出 ValueError字符串)。

      事实上,如果您想确保确实从所有字符串中获取了值,并且所有这些值都放在最后一个空格之后,这是一件好事。你甚至可以添加一个 try...catch 块来做一些事情,以防它试图处理的字符串是一种意外的格式。

      【讨论】:

      • 第 2 行和第 3 行可以合并到first_num, last_num = string.split()[-1].split('..')。
      • 最佳解决方案,在这种情况下不需要正则表达式。
      【解决方案4】:
       first=[(i.split()[1]).split("..")[0] for i in my_list]
       second=[(i.split()[1]).split("..")[1] for i in my_list]
      

      【讨论】:

        猜你喜欢
        • 2011-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-10
        • 2021-10-18
        • 1970-01-01
        • 1970-01-01
        • 2013-07-28
        相关资源
        最近更新 更多