简体   繁体   English

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

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

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

and sub_string = 'the dog'和 sub_string = '狗'

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

ie, return a list with the last occurrence of the substring removed?即,返回一个删除了最后一次出现的 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 的列表?

No built-in will help much you here, since scanning for a substring in a list isn't a supported feature, and doing so in reverse order is doubly hard.在这里没有内置功能对您有很大帮助,因为在list中扫描 substring 不是受支持的功能,并且以相反的顺序执行此操作会加倍困难。 List comprehensions won't do much good either, since making them stateful enough to recognize when you've found your needle would involve adding side-effects to the list comprehension, which makes it cryptic and violates the purpose of functional programming tools.列表推导也不会起到太大作用,因为让它们有足够的状态来识别您何时发现您的针将涉及向列表推导添加副作用,这使得它变得神秘并违反了函数式编程工具的目的。 So you're stuck doing the looping yourself:所以你被困在自己的循环中:

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! 在线尝试!

An alternative approach would be to scan by index, allowing you to del it;另一种方法是按索引扫描,允许您del它; this might be a better solution if you want to modify list1 in place, rather than making a new list :如果您想就地修改list1而不是创建一个新list ,这可能是一个更好的解决方案:

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

Try it online! 在线尝试!

That solution is adaptable to making a new copy by simply changing all references to list1 to list2 , and adding list2 = list1[:] before the loop.该解决方案适用于通过简单地将所有对list1的引用更改为list2并在循环之前添加list2 = list1[:]来制作新副本。

In both cases, you can detect if an item was found at all by putting an else: block on the for ;在这两种情况下,您都可以通过在for上放置else:块来检测是否找到了某个项目; if the else block triggers, you didn't break , because sub_string wasn't found anywhere.如果else块触发,你没有break ,因为在任何地方都找不到sub_string

the problem statement is to: remove the element with the substring as the query问题陈述是:删除以 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 作为查询的元素

so, as I deduce it has two steps.所以,正如我推断的那样,它有两个步骤。

  1. Find the element with the substring.使用 substring 查找元素。
  2. Remove the element.移除元素。

for pattern matching, we can use re module (we can use in as well as mentioned in ShadowRanger's answers)对于模式匹配,我们可以使用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.

EDIT编辑

As ShadowRunner suggested, we can optimize the code with the use of list comprehension with if statement instead of filter function.正如 ShadowRunner 所建议的那样,我们可以使用带有 if 语句的列表解析来优化代码,而不是filter function。

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

You could do it in two steps:您可以分两步完成:

  1. Find the index of last occurrence.查找最后一次出现的索引。
  2. Return all the elements that not match that index.返回与该索引不匹配的所有元素。

Example:例子:

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 Output

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

For more details on finding the index of the last occurrence see this .有关查找最后一次出现的索引的更多详细信息,请参阅

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 ['the dog', 'the cat', 'the dog me', 'cat dog'] output ['狗','猫','狗我','猫狗']

One solution is to traverse the input in reverse order and find the index in the reversed list.一种解决方案是以相反的顺序遍历输入并在反向列表中找到索引。 After that, use the index to slice the input list1 .之后,使用索引对输入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.

相关问题 如何从列表中删除最后一次出现的项目? - How to remove the last occurrence of an item from a list? Python - 从列表中的字符串元素中删除子字符串? - Python - Remove substring from string element in a list? Python - 从作为另一个元素的子字符串的字符串列表中删除任何元素 - Python - Remove any element from a list of strings that is a substring of another element 每次出现元素时,将列表分为子列表,从特定子字符串开始 - Split list into sublists at every occurrence of element starting with specific substring 根据包含子字符串的字典从列表中的子字符串返回匹配值 - Return matching value from substring in a list against dictionary containing substring 从列表中删除与条件匹配的第一个匹配项 - Remove first occurrence that matches criteria from a list 如果从子字符串列表中删除列表中的字符串 - Remove string from list if from substring list Python-列表列表中子字符串的出现 - Python - occurrence of substring in a list of lists 如何找到包含特定元素的嵌套列表的最后一次出现的索引? - How to find the index of the last occurrence of nested list that contains a specific element? 一次删除单个链接列表中的第k个元素 - Remove kth last element from a Singly Linked List in a single pass
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM