繁体   English   中英

从列表中删除最后出现的包含 substring 的元素

[英]Remove last occurrence of element containing substring from a list

所以说我有,list1 = ['the dog', 'the cat', 'cat dog', 'the dog ran home']

和 sub_string = '狗'

我怎样才能返回 list2 = ['the dog', 'the cat', 'cat dog']

即,返回一个删除了最后一次出现的 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 的列表?

在这里没有内置功能对您有很大帮助,因为在list中扫描 substring 不是受支持的功能,并且以相反的顺序执行此操作会加倍困难。 列表推导也不会起到太大作用,因为让它们有足够的状态来识别您何时发现您的针将涉及向列表推导添加副作用,这使得它变得神秘并违反了函数式编程工具的目的。 所以你被困在自己的循环中:

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

在线尝试!

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

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

在线尝试!

该解决方案适用于通过简单地将所有对list1的引用更改为list2并在循环之前添加list2 = list1[:]来制作新副本。

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

问题陈述是:删除以 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 作为查询的元素

所以,正如我推断的那样,它有两个步骤。

  1. 使用 substring 查找元素。
  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 function。

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)

Output

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

有关查找最后一次出现的索引的更多详细信息,请参阅

list1 = ['the dog', 'the cat','the dog me', 'cat dog']
sub_string = 'the dog'

for i in list1[::-1]:
    print(i)
    if sub_string in i:
        list1.remove(i)
        break

output ['狗','猫','狗我','猫狗']

一种解决方案是以相反的顺序遍历输入并在反向列表中找到索引。 之后,使用索引对输入list1进行切片。

idx = next(i for i, s in enumerate(reversed(list1), 1) if sub_string in s)
list2 = list1[:-idx]  # If in-place updates are intended, use `del list1[-idx:]` instead

暂无
暂无

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

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