Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove number from list if the first digit and length are the same

Let's say I have a list of [100, 210, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150] I want to remove any numbers that start with the same digit and have the same length. The result should be: [100, 210, 300, 405, 500, 1850, 2120]

What I have so far is:

for i in installed_tx_calc:
    if (len(str(i)) == 3) and (str(i)[:1] == str(i-1)[:1]):
        installed_tx_calc.remove(i)
    elif str(i)[:2] == str(i-1)[:2]:
        installed_tx_calc.remove(i)

I have a list of [862, 1930, 2496] and my code outputs [1930].

I couldn't find anything when searching, but I feel like I'm missing something obvious.

Thank you for your time.

like image 265
jhnkly Avatar asked Mar 05 '23 19:03

jhnkly


2 Answers

You can create the new list with a list comprehension, using itertools.groupby:

from itertools import groupby

numbers =  [100, 210, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150]

out = [next(group) for key, group in groupby(numbers, key=lambda n: (str(n)[0], len(str(n))))]

print(out)
# [100, 210, 300, 405, 500, 1850, 2120]

We group using the tuple (first digit, length of number), and keep the first number of each group, which we get with next(group).

like image 108
Thierry Lathuille Avatar answered Apr 06 '23 14:04

Thierry Lathuille


Create a new set that will keep unique entries. Then, you may filter according to that set:

unique = set()
mylist = [100, 210, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150]
newlist = []

for num in mylist:
    num_str = str(num)
    length = len(num_str)
    first_digit = num_str[0]
    if (length, first_digit) in unique:
        continue
    newlist.append(num)
    unique.add((length, first_digit))

>>> newlist
[100, 210, 300, 405, 500, 1850, 2120]
like image 20
Shahar Avatar answered Apr 06 '23 15:04

Shahar