Reputation: 2047
i have list with numbers. I want to extract all the numbers with consecutive digits like 444,888,1111 etc.. My following python code with regex is working exactly the way I wanted.
import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []
for num in numbers:
if re.search(r'^(\d)\1+$',num):
conList.append(num)
print('conList :',conList)
Result:
conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']
Now I am trying to achieve the same result without using a regex pattern. How can I replace that regex pattern with some python code? (I am trying this only for educational purpose. I will post my answer if I got one.)
Upvotes: 0
Views: 65
Reputation: 2047
This is my attempt to solve this problem.
for num in numbers:
if len(set(num)) == 1 and len(num) >1:
conList.append(num)
print('conList :',conList)
Or, using list comprehension
conList = [ num for num in numbers if len(num) > 1 and len(set(num)) == 1 ]
print('conList : %s', conList)
Or, using filter
conList = filter(lambda x: len(x) > 1 and len(set(x)) == 1, numbers)
Upvotes: 2
Reputation: 5613
You can do this in one line using list comprehensions as the following:
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567',
'555', '99999', '11211', '11']
conList = [x for x in numbers if x.count(x[0]) == len(x)]
print conList
output:
['44444', '444', '888', '1111', '3333', '555', '99999', '11']
Upvotes: 0
Reputation: 7913
Use a pythonic and fast approach of list comprehension:
[i for i in numbers if len(set(i)) == 1]
Upvotes: 0