2
import re
line = "the heart was made to be broken"
line_split2 = re.split(r'[ \t\n\r, ]+',line)

def chunks(line_split2, n):
    for i in xrange(0, len(line_split2), n):
        yield line_split2[i:i+n]

separate_word = list(chunks(line_split2, 3))

import pprint
pprint.pprint(separate_word)

count = 0
for lines in separate_word:
    count = count + 1
    print count

我正在尝试合并列表以显示为句子并在它们前面显示行号。

1 the heart was
2 made to be
3 broken

有什么建议吗?

4

4 回答 4

2

你可以使用enumerate()

s = ['the heart was', 'made to be', 'broken']

for i, line in enumerate(s, 1):
    print '%d %s' %(i, line)

1 the heart was
2 made to be
3 broken

有关枚举的更多信息,请参阅http://docs.python.org/library/functions.html#enumerate

于 2012-05-05T20:28:08.307 回答
1

用于enumerate()跟踪您所在的行:

for i, word in enumerate(separate_word, 1):
    print i, ' '.join(word)

> 1 the heart was
> 2 made to be
> 3 broken
于 2012-05-05T20:28:20.630 回答
1

无需编写自己的chunks函数。使用itertools 文档grouper中的配方,然后使用它的结果:enumerate

enumerate(grouper(3, line_split2), start = 1)

这是代码grouper

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
于 2012-05-05T20:28:53.670 回答
0

只需在你的 for 循环中使用 join

import re
line = "the heart was made to be broken"
line_split2 = re.split(r'[ \t\n\r, ]+',line)

def chunks(line_split2, n):
 for i in xrange(0, len(line_split2), n):
    yield line_split2[i:i+n]

separate_word = chunks(line_split2, 3)


count = 0
for lines in separate_word:
    count = count + 1
    print count, " ".join(map(str,lines))

1 the heart was
2 made to be
3 broken
于 2012-05-05T20:38:16.320 回答