以下是一个示例解决方案,使用Python中的itertools库的groupby函数来按组和连接元素:
from itertools import groupby
def group_and_join(lst):
result = []
for key, group in groupby(lst):
result.append(''.join(group))
return result
# 示例
data = ['a', 'a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
result = group_and_join(data)
print(result)
输出结果为:
['aa', 'b', 'ccc', 'd', 'ee']
在这个示例中,我们定义了一个名为group_and_join
的函数,它接受一个列表作为参数。我们使用groupby
函数将列表中连续相同的元素分组,并使用join
函数将每个组中的元素连接起来。最后,将每个连接后的组添加到结果列表中,并返回该列表。
请注意,groupby
函数要求输入列表已经排序。如果您的数据无序,您可能需要在使用groupby
函数之前先对列表进行排序。
上一篇:按组和聚合pandas