把一行分成四个单词的Python方法?

把一行分成四个单词的Python方法?,python,string,Python,String,假设我有如下字符串,长度不同,但“单词”的数量总是等于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 我想把它们切碎成像9c755a62和323b3afe 我可以使用正则表达式来匹配精确的格式,但我想知道是否有更直接的方法来实现这一点,因为对于一个简单的问题来说,正则表达式似乎有点过头了。一个简单的方法是: wordlist = words.split() for

假设我有如下字符串,长度不同,但“单词”的数量总是等于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
我想把它们切碎成像
9c755a62
323b3afe


我可以使用正则表达式来匹配精确的格式,但我想知道是否有更直接的方法来实现这一点,因为对于一个简单的问题来说,正则表达式似乎有点过头了。

一个简单的方法是:

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)

免责声明:我没有想到这个模式;不久前,我在一个类似的主题中发现了它。它可以说依赖于一个实现细节,但如果用另一种方式来实现,它会更加难看。

基于

或者基于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)]

这可能是最长最复杂的方法。

这假设没有空间?@merlin2011修正了这一点。我没有在鱼群中看到石斑鱼。你是说群比吗?你试过了吗?@dansalmo,检查一下这一部分为什么不使用
xrange(0,len(splitGiant),4)
这可以减少计算量,因为我的大脑坏了。只是一点提示:Python(PEP8)鼓励
下划线样式
而不是
camelCase
。抱歉@stretch\u armstrong
>>> 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']
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)]
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