所以说我有,list1 =‘狗’,‘猫’,‘猫狗’,‘狗跑回家’
sub_string =“狗”
我如何返回list2 =‘狗’,‘猫’,‘猫狗’
也就是说,返回最后一次删除子字符串的列表?
发布于 2019-09-26 15:33:41
在这里,没有内置的功能对您有很大的帮助,因为扫描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另一种方法是按索引进行扫描,允许您对其进行del;如果您希望修改list1,而不是创建一个新的list,这可能是一个更好的解决方案。
for i, item in enumerate(reversed(list1), 1):
if sub_string in item:
del list1[-i]
break该解决方案适用于创建一个新副本,只需将对list1的所有引用更改为list2,并在循环之前添加list2 = list1[:]。
在这两种情况下,您都可以通过在else:上放置一个for块来检测是否找到了一个条目;如果else块触发了,则没有发现break,因为在任何地方都找不到sub_string。
发布于 2019-09-26 15:45:14
问题语句是:删除以子字符串作为查询的元素。
因此,正如我推断的,它有两个步骤。
对于模式匹配,我们可以使用re模块(我们可以使用in,也可以使用阴影游侠的答案)
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)]发布于 2019-09-26 15:55:15
你可以分两步完成:
示例:
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']有关查找上次事件的索引的详细信息,请参阅这。
https://stackoverflow.com/questions/58120012
复制相似问题