Home > front end >  auto remove value or string from list if it start with
auto remove value or string from list if it start with

Time:11-19

how can i remove the similar value from list if it start with and keep

one of the value if it has alot of

for example this is my code

list_ph = ['8002378990','8001378990','8202378990','8002378920','8002375990','8002378990','8001378890','8202398990']

so this value sould return 3 value when it will remove the value

if i[:5] 

so the result of it will be something like this

['8002378990','8001378990','8202378990']

without i give it specific value or any thing just sub value[:5]

CodePudding user response:

Here is how I would approach this problem.

I would first create two empty lists, one for comparing the first five digits, and the other to save your result, say

first_five = []
res = []

Now, I would loop through all the entries in your list_ph and add the number to res if the first five digits are not already stored in first_five

i.e.

for ph in list_ph:
   if ph[:5] not in first_five:
      first_five.append(ph[:5])
      res.append(ph)

All of your target numbers should be stored in res

  • Related