2

Suppose I have string that look like the following, of varying length, but with the number of "words" always equal to multiple of 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

I would like to chop them into strings like 9c 75 5a 62 and 32 3b 3a fe

I could use a regex to match the exact format, but I wonder if there is a more straightforward way to do it, because regex seems like overkill for what should be a simple problem.

4

4 回答 4

9

一种直接的方法如下:

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)

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

于 2013-06-06T18:26:35.813 回答
1

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

 for x in grouper(words.split(), 4):
    print ' '.join(x)
于 2013-06-06T18:39:33.197 回答
0
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

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

于 2013-06-06T18:43:23.123 回答
0
>>> 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)]
于 2013-06-06T18:41:31.283 回答