![](/img/trans.png)
[英]How can I remove certain strings from a list based on the strings in another list, if those strings differ slightly? More info below
[英]How can I remove members of a list of strings of equal length, based on the presence of specific characters in certain positions of the strings?
如果我没有很好地解释这一点,我很抱歉,但它是这样的:我有一个这样的字符串列表,它们的长度都相同:
list_strings=["abc-df-r-e","abc--daa-q","-ab-c-aub-","cbac-a-c--"]
我有一个整数列表,它们是前一个列表中字符串的位置(所以位置都是从 0 到 9,因为每个字符串的长度都是 10):
list_positions=[2,0,4,7]
我要做的是,对于第二个列表中的每个 position,从第一个列表中删除那些位置中没有“a”、“b”、“c”或“-”的字符串。
在这种情况下,第一个字符串将被删除,因为它在 position 4 中有一个“d”,第三个字符串将被删除,因为它在 position 7 中有一个“u”。所以在这种情况下,Z78E6221F6393D14356681DB398CEDZF1
list_strings=["abc--daa-q","cbac-a-c--"]
我试过这个,但我不知道这是否是最好的方法:
list_approved=["a","b","c","-"]
for i in list_strings:
for j,k in enumerate(i):
if j in list_positions:
if i[j] not in list_approved:
list_strings.remove(i)
else:
pass
提前感谢您的任何回答
具有列表理解的解决方案:
list_strings=["abc-df-r-e","abc--daa-q","-ab-c-aub-","cbac-a-c--"]
list_positions=[2,0,4,7]
list_strings = [s for s in list_strings if not any(ch not in 'abc-' and i in list_positions for i, ch in enumerate(s))]
print(list_strings)
印刷:
['abc--daa-q', 'cbac-a-c--']
编辑:感谢@David Wierichs,一个更快的解决方案:
list_strings = [s for s in list_strings if not any(s[i] not in 'abc-' for i in list_positions)]
一个好的pythonic方法是使用“过滤器”function,它可以从具有特定用户定义过滤器的列表中过滤掉。 为此,您需要 function 知道 list_approved 以便它可以相应地过滤掉,
为此,您可以使用包装器或“部分”function。 出于简单的原因,我们将使用来自 functools 的部分。 此 function 允许在不同时间发送 function arguments,有关更多信息,请查看:
https://docs.python.org/2/library/functools.html#functools.partial
此代码确实会根据您的规则过滤掉
from functools import partial
list_strings=["abc-df-r-e","abc--daa-q","-ab-c-aub-","cbac-a-c--"]
list_positions=[2,0,4,7]
list_approved=["a","b","c","-"]
def filter_out_according_to_position(list_positions, list_approved, currnet_string):
return all([currnet_string[i] in list_approved for i in list_positions])
new_list = list(filter(partial(filter_out_according_to_position, list_positions, list_approved), list_strings))
print(new_list)
希望有帮助
在对列表本身进行迭代时,您可能不会删除元素,因为这会破坏索引并且您不会在最后检查每个元素。 例如,使用您的代码, "cbdc-ac--"
没有经过测试。
letter
,而不是word[idx_letter]
break
来停止内部循环迭代list(list_strings)
,如果列表,这会制作一个副本,然后您可以毫无问题地从list_strings
中删除
for word in list(list_strings):
for idx_letter, letter in enumerate(word):
if idx_letter in list_positions and letter not in list_approved:
list_strings.remove(word)
break
print(list_strings)
另一个要看到的是:使用列表理解保留匹配的单词
list_strings = [word for word in list_strings
if not any(letter not in list_approved and i in list_positions for i, letter in enumerate(word))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.