我有一个数据列表,我需要一次对两个元素执行分组操作。我尝试自己做,但需要太多时间。我有一个很大的列表,所以我需要一种更快的方法。
这是一个示例输入:
lst = [["title1","content1"],["title2","content2"],["title3","content3"],["title4","content4"],["title5","content5"]]
这是一个示例输出:
lst = [["title1","content1 content2"]["title3","content3 content4"],["title5","content5"]]
最佳答案
您可以使用zip_longest()
一次处理两个元素:
from itertools import zip_longest
result = [[first, ' '.join([second, fourth])] if fourth is not None else [first, second]
for (first, second), (_, fourth) in zip_longest(lst[0::2], lst[1::2], fillvalue=(None, None))]
输出:
[['title1', 'content1 content2'], ['title3', 'content3 content4'], ['title5', 'content5']]
关于python - 一次对两个元素进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71919922/