python - 如何将列表中的元素组合到一个新的嵌套列表中?

标签 python regex python-3.x list

我有一个这样的列表“r”:

[["", 1], ["this is a text line", 2], ["this is a text line", 3], ["this is a text line", 4], ["", 5], ["", 6], ["this is a text line", 7],["this is a text line", 8], ["this is a text line", 9], ["this is a text line", 10], ["", 11], ["this is a text line", 12], ["this is a text line", 13], ["this is a text line", 14], ["", 15], ["this is a text line", 16], ["this is a text line", 17], ["this is a text line", 18], ["", 19]]

要知道我的空行和带文本的行在哪里,我过滤了我的列表:

empty = [x[1] for x in r if regex.search("^\s*$", x[0])]
text = [x[1] for x in r if regex.search("\S", x[0])]

输出:

empty = [1, 5, 6, 11, 15, 19]
text= [2, 3, 4, 7, 8, 9, 10, 12, 13, 14, 16, 17, 18]

我想做的是组合文本中的数字,如果它们是按顺序排列的 (text[i]-text[i+1]) = +1(为了定义段落):

finaltext = [[2, 3, 4], [7, 8, 9, 10], [12, 13, 14], [16, 17, 18]]
finaltext including empty = [[2, 3, 4, 5, 6], [7, 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]

如何根据条件对列表中的元素进行分组?

最佳答案

使用 itertools.groupby

from itertools import groupby, zip_longest
grp_list = [list(g) for k,g in groupby(r, lambda x:x[0]=='')]
grp_list = grp_list[1:] if r[0][0] == '' else grp_list
text = [[j[1] for j in i] for i in grp_list]

finaltext = text[::2]
print (finaltext)
#[[2, 3, 4], [7, 8, 9, 10], [12, 13, 14], [16, 17, 18]]

finaltext_including_empty = [i+j for i,j in zip_longest(text[::2], text[1::2], fillvalue=[])]
print (finaltext_including_empty)
#[[2, 3, 4, 5, 6], [7, 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]

groupby 根据条件将列表分组为子列表 block ,这里是 lambda x:x[0]=='',意思是创建一个列表 block 直到指向您看到空字符串的位置,并遵循此规则直到结束,如下所示

[[['', 1]], [['this is a text line', 2], ['this is a text line', 3], ['this is a text line', 4]], [['', 5], ['', 6]],........]

关于python - 如何将列表中的元素组合到一个新的嵌套列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248991/

相关文章:

python - 多处理:如何确定作业是正在等待还是已提交?

python - 如何在 Django 模板中从 Matplotlib 输出图形?

python - 使用 Python 清理 HTML 内容

ios - objective-c 中的正则表达式正负十进制值

regex - 从单元格中提取唯一文本字符/表情符号的列表

python - django rest-framework中身份验证和权限之间的区别

将匹配除括号中的内容以外的所有内容的正则表达式

python - 为什么 enumerate、zip、range 类型不属于 types.GeneratorType?

python-3.x - 在某些条件下使用计数方法重新采样数据帧

python - 在同一个方法中使用两个父方法