user3496060 user3496060 - 5 months ago 13
Python Question

Convert a for loop to a list comprehension

I have a

for
loop that compares a substring of each element in a list of strings to the elements in another list of strings.

mylist = []
for x in list1:
mat = False
for y in list2:
if x[:-14] in y:
mat = True
if not mat:
mylist.append(x)


However I would like to put it in a list comprehension (for loops aren't as concise for my tastes) But can't find a way to do it with the calculation of
mat
.

I have tried variations on:

mylist = [x for x in list1 if x[:-14] in list2]


But this is not the same logic as the original loop. Is there a way to reform the original for loop into list comprehension?

Answer

As it is written, no you cannot directly write it as list comprehension.

however if you rewrite the computation of mat to use the builtin any like this:

mylist = []
for x in list1:
    mat = any((x[:-14] in y) for y in list2)
    if not mat:
        mylist.append(x)

Then move the use of any directly into the if not:

mylist = []
for x in list1:
    if not any((x[:-14] in y) for y in list2):
        mylist.append(x)

Now it is pretty strait forward to convert:

mylist = [x for x in list1 if not any((x[:-14] in y) for y in list2)]