找出包含常见重复元素的所有子列表的长度



我需要从元素为"F"的列表中找到所有子列表,并且必须一个接一个地出现在中

g= ['T','F','F,'F','F','T','T','T','F,'F','F','T]

因此,在这种情况下,这个列表中有两个子列表,其中包含重复中的元素'F'

i.e; ['F','F,'F','F'] in index 1,2,3,4 which is in repeat ,so answer is 4
and
['F','F,'F'] in index 8,9,10 which is again in continuous index,so answer is 3

注:该列表只包含两个元素'T''F',每次我们对元素'F'进行这些操作时

您可以使用itertools.groupby:获取连续序列的长度

from itertools import groupby
data = ['T','F','F','F','F','T','T','T','F','F','F','T']
# Consecutive sequences of "F".
#   "groupby(data)" produces an iterator that calculates on-the-fly.
#   The iterator returns consecutive keys and groups from the iterable "data".
seqs = [list(g) for k, g in groupby(data) if k == 'F']
print(seqs)
# [['F', 'F', 'F', 'F'], ['F', 'F', 'F']]
seq_lens = [len(k) for k in seqs]
print(seq_lens)
# [4, 3]

同样酷的是这种连续序列的最大长度:

max_len_seq = len(max(seqs, key=len))
print(max_len_seq)
# 4

有关更多信息,请参阅itertools.groupby:

class groupby:
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
...
etc

您可以创建2个变量来保持重复字母的计数。遍历数组,当你发现t增加t时,当你找到f时,首先检查tcount,如果它大于1,这意味着有一个重复打印重复的计数。

tcount = 0;
fcount = 0;
for e in g:
if e=="T":
tcount++
if fcount>1
print(fcount)
fcount=0
//do same operation for F

相关内容

  • 没有找到相关文章

最新更新