newbie newbie - 2 years ago 76
Python Question

Find the 1st occurence of elements in a list of strings, based on first character in the string

I am new to python. I am trying to get the 1st number in a list of strings that are numbers in a series, that start with a common number.


x = ['512','345','321','345','674','132','231','145','214','576']

my expected output:

result = ['512','345','674','132','231']

i.e say for example in all numbers starting with 1 in list, I should get the 1st number likewise for all other numbers.

I could use for loop twice to get it. but i want to know is there any better way of doing it.

NOTE: the list is a list of strings which are numbers given was just an example.

Answer Source

You can use a generator function to do this. In the function you just iterate your initial list and for each element check if there is another element that starts with the same character already exists in a set of string. If no match found, just yield that element.

>>> def get_num(lst):
...     found = set()
...     for element in lst:
...         if not any(item.startswith(element[0]) for item in found):
...             found.add(element)
...             yield element
>>> x = ['512','345','321','345','674','132','231','145','214','576']
>>> list(get_num(x))
['512', '345', '674', '132', '231']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download