[英]How to check if any of the elements in a list can be found in the given string?
[英]Removing elements of a list if they can be found in some given string in Python
如果可以在字符串中的某处找到列表中的元素,我会尝试删除它们。
但不知何故,最终列表包含肯定不在字符串中的元素。
有人可以指出我正确的方向吗? 不确定是不是因为列表在循环或类似的情况下被改变了。
这是我的代码:
big_string = '209301293012931234847123'
small_strings = ['1', '2', 'sugar', 'juice', '666']
for element in small_strings:
if element not in big_string:
small_strings.remove(element)
print(small_strings)
我期望的输出是:
['1', '2']
相反,我得到的是:
['1', '2', 'juice']
注意:如果我复制列表并仅修改该列表(使用另一个作为参考),它似乎可以完美运行。 这是为什么? 除了创建副本之外,还有其他方法可以做到吗?
我们可以在这里尝试使用列表推导式:
small_strings_out = [x for x in small_strings if x not in big_string]
print(small_strings_out)
这打印:
['sugar', 'juice', '666']
您会得到意想不到的结果,因为您正在更改 for 循环内的列表。 做你想做的最简单的方法是制作列表的副本。 但是,如果您绝对必须就地编辑列表,则可以使用 while 循环。
big_string = '209301293012931234847123'
small_strings = ['1', '2', 'sugar', 'juice', '666']
current_index = len(small_strings) - 1
while current_index >= 0:
element = small_strings[current_index]
if element not in big_string:
small_strings.pop(current_index)
current_index -= 1
print(small_strings)
此代码在列表上向后循环,因为 pop() 在删除靠近列表末尾的元素时具有更好的性能。 但是,如果可以节省额外的内存,制作列表副本可能比使用 while 循环更快。 (尽管与所有与性能相关的事情一样,您应该在优化任何事情之前进行衡量。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.