简体   繁体   English

如何从字符串列表中删除子字符串列表

[英]How to remove a list of substrings from a list of strings

I can find lots of advice re: removing a list of substrings from a string but very little / none on removing a list of substrings from a list of strings.我可以找到很多建议:从字符串中删除子字符串列表,但很少/没有从字符串列表中删除子字符串列表。

My data is as such:我的数据是这样的:

List 1: [Op 18 TC 16, TC 20, OP 15 TC 80]清单 1:[Op 18 TC 16、TC 20、OP 15 TC 80]

List 2: [Op 18, , OP 15]清单 2: [Op 18, , OP 15]

Expected result: a final list containing: [TC 16, TC 20, TC 80]预期结果:最终清单包含:[TC 16、TC 20、TC 80]

I am aware that I will need to account for spaces and such and the answer may well be obvious / staring me in the face but I just cant seem to crack this one.我知道我需要考虑空格等,答案可能很明显/盯着我的脸,但我似乎无法破解这个。

I have tried for loop within a for loop but end up with the obvious multitude of values in the final list and I have tried a list comprehension that I thought would work but it had no affect.我在 for 循环中尝试了 for 循环,但最终在最终列表中得到了明显的大量值,我尝试了一个我认为可行但没有影响的列表理解。

If I need to improve the question please tell me, but please help as I am stuck on this one如果我需要改进这个问题,请告诉我,但请帮忙,因为我被困在这个问题上

Try this:尝试这个:

lst1 = ['Op 18 TC 16', 'TC 20', 'OP 15 TC 80']
lst2 = ['Op 18', 'OP 15']

result = []
for s1 in lst1:
    tmp = s1
    for s2 in lst2:
        tmp = tmp.replace(s2, '')
    result.append(tmp.strip())

Here is the result这是结果

>>> result
['TC 16', 'TC 20', 'TC 80']

You can do it by looping the second array and removing the items from the first see below:您可以通过循环第二个数组并从第一个数组中删除项目来做到这一点,如下所示:

listOne = ["Op 18", "Op 18", "TC 16", "TC 20", "OP 15", "TC 80"]
listTwo =  ["Op 18", "OP 15"]

for string in listTwo:
    try:
        while True:
            listOne.remove(string)
    except ValueError:
        pass

print(listOne)
# ['TC 16', 'TC 20', 'TC 80']

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

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