2016-09-16 151 views
0

有没有一种方法来测试列表中的项目是否具有5位及以上的重复,并且重复彼此相邻?列表中的Python迭代

#!/usr/bin/env python 
import itertools 
from collections import Counter 

mylist = ['000002345','1112345','11122222345','1212121212'] 

#some function code here 

#expected output 
#['000002345','11122222345'] #1 and 2 repeats five times, next to each other 

#method 1 
v = list(mylist[0]) 

for i in v: 
    if v[0]==v[1] and v[0]==v[1]... 

#method 2 
v = list(mylist[0]) 
Counter(v) 

我只能想到用if语句,但我的实际列表很长,如果项目包含在项目之间的重复,如“1123333345”,这需要我从来不写这将是低效结束ifs'。

考虑到我的第二种方法,在知道有多少次重复之后我不太确定如何进行,即使如此,它将返回具有五次重复但彼此不相邻的项目,例如'1212121212 ”。

任何想法?

回答

2

的条件是我只想用5 位的重复和上述

使用一个regular expression的项目:

>>> import re 
>>> mylist = ['000002345', '1112345', '11122222345', '1212121212'] 
>>> for item in mylist: 
...  if re.search(r'(\d)\1{4,}', item): 
...   print(item) 
... 
000002345 
11122222345