python - 在列表中查找最长的不间断公共(public)元素

标签 python algorithm list

我有这个列表,其中只包含 Ws 和 Ss:

ls = ['W', 'S', 'S', 'S', 'W', 'W', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'W', 'W', 'W', 'W', 'W', 'W', 'S'] 

我想做的是提取该列表中最长的不间断“S”? 并返回该 Ss 的索引,返回:

['S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S']

[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

我怎样才能做到这一点?

最佳答案

使用itertools.groupbyenumeratemax :

>>> from operator import itemgetter
>>> from itertools import groupby
>>> val = max((list(g) for k, g in
                   groupby(enumerate(ls), itemgetter(1)) if k == 'S'), key=len)
>>> indices, items = zip(*val)
>>> indices
(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
>>> items
('S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S')

关于python - 在列表中查找最长的不间断公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476771/

相关文章:

python - 如何在 python 中模拟 pyplot.show(以防止显示图)

python - 逻辑回归无法拟合我的数据

Python Rest API POST 图像

algorithm - 为什么 Interval.contains(Interval) 需要包含 other.start < this.end 条件?

html - CSS float 列表项

python - Pandas 数据框合并/链接值

c++ - 通过网络直接从另一台计算机的内存中读取文件

python - 查找可能的唯一固定长度排列数的最有效方法?

c++ - 使用 Push、Pop 等在 C++ 中创建堆栈

python - 将元素附加到嵌套列表中的列表 - python