Hezron Barnabas - 1 month ago 4x
Python Question

Python Iteration in list

Is there a way to test whether an item in a list has repetitions of 5 digits and above, and the repetitions being adjacent to each other?

``````#!/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)
``````

I can only think of using if statements, but my actual list is pretty long and it will be inefficient if the item contains repetitions in between an item, such as '1123333345', which requires me to write never ending ifs'.

With my second method in mind, I'm not too sure how to proceed after knowing how many repetitions are there, and even so, it will return items having five repetitions but not adjacent to each other, such as '1212121212'.

Any ideas?

The condition is that i only want the items with a repetition of 5 digits and above

Use a 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
``````
Source (Stackoverflow)