简体   繁体   English

如果某个字母在某个 position 中,则尝试从字符串列表中删除任何字符串

[英]Trying to remove any string from a list of strings, if a letter is in a certain position

I am trying to search a list of strings and if it has a letter in a certain character position, I want to remove that string from the list.我正在尝试搜索字符串列表,如果它在某个字符 position 中有一个字母,我想从列表中删除该字符串。 So far I have:到目前为止,我有:

l = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']

for strings in l:
if 'a' in strings[0]:
    l.pop()

print(l)

Thanks.谢谢。

Well, first I would say that pop is not the best option for the procedure.好吧,首先我要说 pop 不是该过程的最佳选择。 pop will return the value, you are only looking to remove it. pop 将返回该值,您只是想删除它。 To remove an element from a list given its index you can do:要从给定索引的列表中删除元素,您可以执行以下操作:

my_list = [1,2,3,4]
del(my_list[2])

Nevertheless, going through a for loop while removing the elements that are part of it is not a good idea.然而,通过 for 循环同时删除属于它的一部分的元素并不是一个好主意。 It would be best to create a new list with only the elements you want.最好创建一个仅包含您想要的元素的新列表。

my_list = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
my_new_list = []
for value_str in my_list:
    if 'a' != value_str[0]:
        my_new_list.append(value_str)

This can also be done more concisely using list comprehension.这也可以使用列表推导更简洁地完成。 The snippet below does the same thing as the one above, but with less code.下面的代码片段与上面的代码片段相同,但代码更少。

my_list = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
my_new_list = [value_str for value_str in my_list if value_str[0] != 'a']

Tim already gave you that snippet as an answer, but I felt that given the question it would be better to give you a more descriptive answer.蒂姆已经给了你那个片段作为答案,但我觉得考虑到这个问题,最好给你一个更具描述性的答案。

This is a good link to learn more about list comprehensions, if you are interested (they are pretty neat): Real Python - List Comprehensions如果您有兴趣,这是了解更多关于列表理解的好链接(它们非常简洁): Real Python - 列表理解

Using a list comprehension we can try:使用列表推导,我们可以尝试:

l = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
output = [x for x in l if x[0] != 'a']
print(output)  # ['fast', 'slow', 'baft', 'baft']

You can use str.startswith method to check if a string starts with a certain character (in this case 'a' ) and use list comprehension to create a new list of strings where none of the strings start with 'a' (since we don't want strings that start with 'a' , we put in not )您可以使用str.startswith方法检查字符串是否以某个字符开头(在本例中'a' ),并使用列表推导创建一个新的字符串列表,其中没有字符串以'a'开头(因为我们不'不想要以'a'开头的字符串,我们输入not )

out = [string for string in l if not string.startswith('a')]

Output: Output:

['fast', 'slow', 'baft', 'baft']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM