代码之家  ›  专栏  ›  技术社区  ›  Souradeep Nanda

如何从同一行中提取冒号分隔值?

  •  0
  • Souradeep Nanda  · 技术社区  · 8 年前

    我正在使用python正则表达式。我要把所有冒号分隔的值排成一行。

    input = 'a:b c:d e:f'
    
    expected_output = [('a','b'), ('c', 'd'), ('e', 'f')]
    

    但当我这么做的时候

    >>> re.findall('(.*)\s?:\s?(.*)','a:b c:d')
    

    我明白了

    [('a:b c', 'd')]
    

    >>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d')
    [('a', 'b')]
    
    4 回复  |  直到 8 年前
        1
  •  2
  •   Jannes    8 年前

    以下代码对我有效:

    inpt = 'a:b c:d e:f'
    re.findall('(\S+):(\S+)',inpt)
    

    输出:

    [('a', 'b'), ('c', 'd'), ('e', 'f')]
    
        2
  •  2
  •   Vikas Periyadath Ramana Sriwidya    8 年前

    :

    inpt = 'a:b c:d e:f'
    k= [tuple(i.split(':')) for i in inpt.split()]
    print(k)
    
    # [('a', 'b'), ('c', 'd'), ('e', 'f')]
    
        3
  •  1
  •   Kaushik NP    8 年前

    最简单的使用方法 list comprehension split

    [tuple(ele.split(':')) for ele in input.split(' ')]
    

    #驱动程序值:

    IN : input = 'a:b c:d e:f'
    OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')]
    
        4
  •  1
  •   Swadhikar    8 年前

    你可以用

    list(map(lambda x: tuple(x.split(':')), input.split()))
    

    哪里

    input.split()

    >>> input.split()
    ['a:b', 'c:d', 'e:f']
    

    lambda x: tuple(x.split(':')) 是将字符串转换为元组的函数 'a:b' => (a, b)

    map 将上述函数应用于所有列表元素并返回一个映射对象(在Python 3中),并使用 list

    >>> list(map(lambda x: tuple(x.split(':')), input.split()))
    [('a', 'b'), ('c', 'd'), ('e', 'f')]