[英]Find the 1st occurence of elements in a list of strings, based on first character in the string
I am new to python. 我是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.
我试图在一个字符串列表中获取第一个数字,这些字符串是一个系列中的数字,以一个公共数字开头。
ex: 例如:
x = ['512','345','321','345','674','132','231','145','214','576']
my expected output: 我的预期输出:
result = ['512','345','674','132','231']
ie say for example in all numbers starting with 1 in list, I should get the 1st number likewise for all other numbers. 也就是说例如在列表中以1开头的所有数字中,我应该同样获得所有其他数字的第一个数字。
I could use for loop twice to get it. 我可以使用for循环两次来获取它。 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. 注意:列表是一个字符串列表,给出的数字只是一个例子。
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. 在函数中,您只需迭代初始列表,并为每个元素检查是否有另一个以相同字符开头的元素已经存在于一
set
字符串中。 If no match found, just yield
that element. 如果发现不匹配,就
yield
该元素。
>>> 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.