Filtering Items Based on Digit Positions in Python
In this example, we filter a list of strings based on a specific digit pattern. The goal is to find all items where the last digit is equal to the third-from-last digit, but only if those digits are between 0
and 5
.
Filter Logic
- Check if the string length is at least 3.
- Check if
item[-1] == item[-3]
. - Check if that digit is in the set
{'0', '1', '2', '3', '4', '5'}
.
This helps identify patterns like '770410232'
where the last digit '2'
matches the third-from-last digit '2'
.
Filtered Items List
filtered_items = [
'770410232', '770410252', '770410353', '770410434', '770410454', '770410535', '770410545',
'770411232', '770411252', '770411343', '770411353', '770411454', '770411535', '770411545',
'770412353', '770412434', '770412454', '770412535', '770412545', '770413202', '770413212',
'770413242', '770413252', '770413414', '770413424', '770413454', '770413515', '770413525',
'770413545', '770414313', '770414323', '770414515', '770414525', '770414535', '770415121',
'770415202', '770415212', '770415232', '770415242', '770415303', '770415313', '770415343',
'770415404', '770415424', '771140151', '771140232', '771140242', '771140252', '771140343',
'771140535', '771140545', '771141232', '771141242', '771141252', '771141343', '771141535',
'771142131', '771142141', '771142313', '771142343', '771142535', '771142545', '771143101',
'771143121', '771143141', '771143151', '771143242', '771143252', '771143505', '771143515',
'771143525', '771144131', '771144232', '771144303', '771144313', '771144323', '771144515',
'771144525', '771144535', '771145101', '771145121', '771145131', '771145141', '771145202',
'771145212', '771145232', '771145242', '771145313', '771145343',
]
Summary
This filtered list contains all items matching the digit pattern rule described above. The approach can be adapted for other positional digit checks or patterns in strings.
Top comments (0)