Python:如何合并显示为句子和显示行号
我试图合并列表以显示为句子,并在它们前面显示行号Python:如何合并显示为句子和显示行号,python,Python,我试图合并列表以显示为句子,并在它们前面显示行号 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(
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
有什么建议吗 您可以使用
枚举()
:
有关枚举的更多信息,请参见您可以使用
enumerate()
:
有关枚举的更多信息,请参见使用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
使用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
无需编写自己的
块
函数。使用来自的石斑鱼
配方,然后根据结果使用:
for i, word in enumerate(separate_word, 1):
print i, ' '.join(word)
> 1 the heart was
> 2 made to be
> 3 broken
以下是grouper的代码:
enumerate(grouper(3, line_split2), start = 1)
无需编写自己的
块
函数。使用来自的石斑鱼
配方,然后根据结果使用:
for i, word in enumerate(separate_word, 1):
print i, ' '.join(word)
> 1 the heart was
> 2 made to be
> 3 broken
以下是grouper的代码:
enumerate(grouper(3, line_split2), start = 1)
只需在for循环中使用join
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)
只需在for循环中使用join
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)
@ThanaDaray我刚刚更新了我的答案,它与您的question@ThanaDaray我刚刚更新了我的答案,它与你问题中的
行列表(chunks(line\u split2,3))
生成的单独单词列表一起工作