I am trying to create a new list based on a subset of elements. The selection criteria is a partial string. I have a working example, but I am trying to code this in a cleaner way such that the selection criteria itself is a list of elements.
I want the source list element (which is itself a list) to be added to the new list only if multiple substrings are not present in any of the source list sub-elements.
Here is my working example code:
links = [['abc', 'def'], ['ghi', 'jkl'], ['def', 'xyz']]
sublinks = []
for link in links:
if ((('ab' not in link[0]) and ('ab' not in link[1])) and
(('xy' not in link[0]) and ('xy' not in link[1]))):
sublinks.append(link)
From the links
list, this achieves the result of appending only the element ['ghi', 'jkl']
since it is the only element from the source list that passes the matching criteria of elements not containing ab
or xy
in any of the sub-elements.
The example code shows the logic I am trying to achieve, but I would instead like to place ab
and xy
into a list so that I can specify an arbitrary number of matching criteria. The format of the source list (a list of lists with two elements) will remain the same.
I have spent several hours trying to answer my own question, searching stackoverflow, trying to figure it out on my own, but I haven't had any success yet and any help is greatly appreciated! Thank you
question from:
https://stackoverflow.com/questions/65890470/python-append-to-list-only-if-multiple-elements-are-not-in-another-list 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…