我有这个列表只包含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]
我怎样才能做到这一点?
答案 0 :(得分:11)
将itertools.groupby
与enumerate
和max
一起使用:
>>> 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')
答案 1 :(得分:3)
与Ashwini Chaudhary相同的解决方案减去了优雅,
from itertools import groupby
index, result, m_index = 0, [], 0
# Group based on the elements of the list
for item, grp in groupby(ls):
# Get the grouped items as a list
grp = list(grp)
# Filter out `M`s and check if this is the biggest run of `S`s ever seen
if item == "S" and len(grp) > len(result):
result, m_index = grp, index
# Increment the index to keep track of the list covered
index += len(grp)
print(result, list(range(m_index, m_index + len(result))))
答案 2 :(得分:3)
>>> import re
>>> max((x.group(), x.span()) for x in re.finditer("S+", "".join(ls)))
('SSSSSSSSSSS', (6, 17))
>>> range(6, 17)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
答案 3 :(得分:-1)
package com.algo.sort;
公共类LargestCont {
static int g[]={1,1,1,1,2,2,3,4,5,5,5,5,5,5,5,5,5,5,5,2,2,2,2,3,3,3,3,3,3,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0};
public static void main(String f[]){
manage(g);
}
public static void manage(int[] j){
int max=1; int val=-1; int count=0; int ans=0;
for(int i=0;i<j.length;i++){
if(j[i]!=val){
if(max>count){
ans=val;
count=max;
System.out.println(ans+"...."+count);
}
val=j[i]; max=1;}else{
max++;
}
}
System.out.println(ans);
}
}
答案 4 :(得分:-2)
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']
for x,y in enumerate(ls):
print (x,str(y).split("W"))
我找到了这个。