【问题标题】:Pythonic way to split a line into groups of four words? [duplicate]将一行分成四个单词的 Pythonic 方法? [复制]
【发布时间】:2013-06-02 21:26:39
【问题描述】:

假设我的字符串如下所示,长度不等,但“单词”的数量始终等于 4 的倍数。

9c 75 5a 62 32 3b 3a fe 40 14 46 1c 6e d5 24 de
c6 11 17 cc 3d d7 99 f4 a1 3f 7f 4c

我想把它们切成像9c 75 5a 6232 3b 3a fe这样的字符串

我可以使用正则表达式来匹配确切的格式,但我想知道是否有更直接的方法可以做到这一点,因为正则表达式对于应该是一个简单的问题来说似乎有点矫枉过正。

【问题讨论】:

    标签: python string


    【解决方案1】:

    执行此操作的直接方法如下:

    wordlist = words.split()
    for i in xrange(0, len(wordlist), 4):
        print ' '.join(wordlist[i:i+4])
    

    如果由于某种原因您无法列出所有单词(例如无限流),您可以这样做:

    from itertools import groupby, izip
    words = (''.join(g) for k, g in groupby(words, ' '.__ne__) if k)
    for g in izip(*[iter(words)] * 4):
        print ' '.join(g)
    

    免责声明:我没有想出这种模式;不久前,我在一个类似的主题中找到了它。可以说它依赖于一个实现细节,但如果以不同的方式完成,它会更加丑陋。

    【讨论】:

    • 这里假设没有空格?
    • @merlin2011 已修复。
    【解决方案2】:

    一种基于itertools grouper recipe的稍微实用的方法

     for x in grouper(words.split(), 4):
        print ' '.join(x)
    

    【讨论】:

    • 我没有在 intertools 中看到石斑鱼。你是说groupby吗?你试过这个吗?
    • @dansalmo,查看recipe 部分
    【解决方案3】:
    giantString= '9c 75 5a 62 32 3b 3a fe 40 14 46 1c 6e d5 24 de c6 11 17 cc 3d d7 99 f4 a1 3f 7f 4c'
    
    splitGiant = giantString.split(' ')
    stringHolders = []
    for item in xrange(len(splitGiant)/4):
        stringHolders.append(splitGiant[item*4:item*4+4])
    
    stringHolder2 = []
    
    for item in stringHolders:
        stringHolder2.append(' '.join(item))
    
    print stringHolder2
    

    最复杂的方式来做到这一点。

    【讨论】:

    • 为什么不用xrange(0, len(splitGiant), 4) 这样可以减少计算量
    • 因为我的脑子坏掉了。
    • 一点提示:Python (PEP8) 鼓励 underscore_style 超过 camelCase
    • 对不起@stretch_armstrong
    【解决方案4】:
    >>> words = '9c 75 5a 62 32 3b 3a fe 40 14 46 1c 6e d5 24 de'.split()
    >>> [' '.join(words[i*4:i*4+4]) for i in range(len(words)/4)]
    ['9c 75 5a 62', '32 3b 3a fe', '40 14 46 1c', '6e d5 24 de']
    

    或基于 1_CR 的回答

    from itertools import izip_longest
    
    def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
        args = [iter(iterable)] * n
        return izip_longest(fillvalue=fillvalue, *args)
    
    [' '.join(x) for x in grouper(words.split(), 4)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 2020-12-29
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多