我有一个带有字符串的列表列表,类似于这样(表示文本的章节、段落和句子)):
[ [[ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'] ],
[ ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ]],
[[ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'] ],
[ ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ]] ]
我知道如何将此列表完全展平(例如通过[x for y in z for x in y]
),但我想做的是将其部分展平,最终如下所示:
[ [ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'],
['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ],
[ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'],
['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ] ]
我通过一些for循环解决了这个问题:
semiflattend_list=list()
for chapter in chapters:
senlist=list()
for paragraph in chapter:
for sentences in paragraph:
senlist.append(sentences)
semiflattend_list.append(senlist)
但我想知道有没有更好、更短的解决方案?(我不认为zip
是一种方式,因为我的列表大小不同。)
我能看到的最简单的变化是使用
itertools.chain
方法:那么,
[list(itertools.chain(*g)) for g in q]
是什么意思:相关问题 更多 >
编程相关推荐