从lis中删除包含子字符串的元素的最后一个匹配项

2024-04-25 19:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有,list1=['狗','猫','猫狗','狗跑回家']

和sub_string='狗'

如何返回list2=['狗','猫','猫狗']

也就是说,返回一个删除了最后一次出现的子字符串的列表?你知道吗


Tags: 字符串列表stringlist2list1回家
3条回答

在这里,没有任何内置功能对您有多大帮助,因为在list中扫描子字符串是不受支持的功能,而且以相反的顺序进行扫描是非常困难的。列表理解也不会有多大的好处,因为让它们有足够的状态来识别何时发现了自己的指针将涉及到给列表理解添加副作用,这使得列表理解变得晦涩难懂,违反了函数式编程工具的目的。所以你被困在自己做循环:

list2 = []
list1iter = reversed(list1)  # Make a reverse iterator over list1
for item in list1iter:
    if sub_string in item:   # Found item to remove, don't append it, we're done
        break
    list2.append(item)       # Haven't found it yet, keep item
list2.extend(list1iter)      # Pull all items after removed item
list2.reverse()              # Put result back in forward order

Try it online!

另一种方法是按索引扫描,允许您del它;如果您想就地修改list1,而不是创建新的list,这可能是更好的解决方案:

for i, item in enumerate(reversed(list1), 1):
    if sub_string in item:
        del list1[-i]
        break

Try it online!

该解决方案可以通过简单地将对list1的所有引用更改为list2,并在循环之前添加list2 = list1[:]来生成新副本。你知道吗

在这两种情况下,您都可以通过在for上放置else:块来检测是否找到了项;如果else块触发,您就没有break,因为在任何地方都找不到sub_string。你知道吗

问题陈述是:删除子字符串作为查询的元素

所以,我推断它有两个步骤。你知道吗

  1. 找到包含子字符串的元素。你知道吗
  2. 拆下滤芯。你知道吗

对于模式匹配,我们可以使用re模块(我们可以使用in以及ShadowRanger的答案中提到的)

import re

pattern = re.compile('the dog') # target pattern 
my_list = ['the dog', 'the cat', 'cat dog', 'the dog ran home'] # our list
my_list = enumerate(my_list) # to get indexes corresponding to elemnts i.e. [(0, 'the dog'), (1, 'the cat'), (2, 'cat dog'), (3, 'the dog ran home')]
elems = list(filter(lambda x: pattern.search(x[1]), my_list) # match the elements in the second place and filter them out, remember filter in python 3.x returns an iterator
print(elems) # [(0, 'the dog'), (3, 'the dog ran home')]
del my_list[elems[-1][0]] # get the last element and take the index of it and delete it.

编辑

正如ShadowRunner所建议的,我们可以使用if语句的列表理解来优化代码,而不是使用filter函数。你知道吗

elems = [i for i, x in enumerate(my_list) if pattern.search(x)]

你可以分两步来做:

  1. 查找上次出现的索引。你知道吗
  2. 返回与该索引不匹配的所有元素。你知道吗

示例:

needle = 'the dog'
haystack = ['the dog', 'the cat', 'cat dog', 'the dog ran home']

last = max(loc for loc, val in enumerate(haystack) if needle in val)
result = [e for i, e in enumerate(haystack) if i != last]

print(result)

输出

['the dog', 'the cat', 'cat dog']

有关查找最后一次出现的索引的详细信息,请参见this。你知道吗

相关问题 更多 >