如何查看列表中是否存在第一个字符(python)



我想看看列表中的元素是否有一个特定的字符作为它的第一个字符,我想检查每个元素:例如,如果我有一个包含4个随机字符串的列表,并且我想看看字母a是否是列表中任何字符串的第一个字符

您可以使用列表理解来使用字符串方法startswith():解决此问题

mylist=['this is a string', 'and so is this', 'and one more', 'here is the last']    
outlist=[x for x in mylist if x.startswith('a')]
print(outlist)

这在功能上相当于:

mylist=['this is a string', 'and so is this', 'and one more', 'here is the last']
outlist=[]
for x in mylist: 
if x.startswith('a'):
outlist.append(x)
print(outlist)

您可以为其使用list.filter功能

>>> words = ["hello", "foo", "bar", "fred"]
>>> print(list(filter(lambda word: word.startswith("f"), words)))
['foo', 'fred']

最新更新