本文介绍了python列表操作以比较元素的一部分而不是完整的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,我只想处理部分不匹配的元素.

I have two lists and I want to process only the elements part of which do not match.

ListA = ['CAT.txt','CAT.txt.ext','DOG.txt','DOG.txt.ext','TIGER.txt.ext',TIGER.txt']ListB = ['CAT_NEW.txt','CAT_NEW.txt.ext','TIGER_NEW.txt','TIGER_NEW.txt.ext']

ListA = ['CAT.txt','CAT.txt.ext','DOG.txt','DOG.txt.ext','TIGER.txt.ext',TIGER.txt']ListB = ['CAT_NEW.txt','CAT_NEW.txt.ext', 'TIGER_NEW.txt', 'TIGER_NEW.txt.ext']

列表B是列表A的子集,带有"_NEW"

List B is a subset of list A with "_NEW"

我想要的输出:ListC = ['DOG.txt','DOG.txt.ext']

Output I want: ListC = ['DOG.txt', 'DOG.txt.ext']

这是我遇到的另一个问题的解决方法:.检查了多个线程,但是.txt.ext很难拆分...

This is a work around for another question I had asked : Python: Trying to check if file exists and if not create new files and final output list . Checked multiple threads but the .txt.ext is hard to split on...

如图所示,如果我拆分了输入列表,则可以在不检查日志文件的情况下实现.

Figured if I split the input lists, I can implement without checking for the log file.

我检查了这个问题:

I checked this : Python: how to find the element in a list which match part of the name of the element

推荐答案

从 ListB 中移除字符串 '_NEW',并使用 set 操作:

Remove the strings '_NEW' from the ListB, and use set operation:

In [1]: ListA = ['CAT.txt','CAT.txt.ext','DOG.txt','DOG.txt.ext','TIGER.txt.ext','TIGER.txt']                                 

In [2]: ListB = ['CAT_NEW.txt','CAT_NEW.txt.ext', 'TIGER_NEW.txt', 'TIGER_NEW.txt.ext']                                       

In [3]: lb= [ s.replace("_NEW","") for s in ListB ]                                                                           

In [4]: lb                                                                                                                    
Out[4]: ['CAT.txt', 'CAT.txt.ext', 'TIGER.txt', 'TIGER.txt.ext']

In [5]: list(set(ListA)-set(lb))                                                                                              
Out[5]: ['DOG.txt', 'DOG.txt.ext']

这篇关于python列表操作以比较元素的一部分而不是完整的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!