简体   繁体   English

根据字符串中的第一个字符,查找字符串列表中第一个元素的出现位置

[英]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.

相关问题 Append x 第一次出现在列表中并中断循环。 但是,如果 y 出现在 x 之前,append y 第一次出现,则忽略 y 直到 x 第一次出现 - Append 1st occurence of x to a list and break loop. However, if y occurs before x, append 1st occurrence of y, then ignore y until 1st occurence of x 替换字符串中第一次跳过时出现的字符 - Replace the occurrence of a character in string skipping first occurence 在第一次出现字符之前插入字符串 - Insert string before first occurence of character 根据值元素的首次出现过滤字典 - Filtering a dictionary based on the first occurence of the value elements 从数据集中的字符串列表中查找出现 - Find the occurence from the list of strings in the dataset 从列表中删除空字符串,Python 中的第一个除外 - Remove empty strings from a list except 1st one in Python 我想在第一次出现时用一个字符分割一个字符串,该字符属于一个字符列表。 如何在python中做到这一点? - I want to split a string by a character on its first occurence, which belongs to a list of characters. How to do this in python? 根据第二列中存在的字符串更新第一列 - Update 1st column based on string present in 2nd column 检查文本/字符串是否存在预定义的列表元素 - Check text/string for occurence of predefined list elements 我想用列表中的第一次出现替换字符串 - I want to replace the string with the first occurence in list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM