Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

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

however, if you rewrite the computation of mat to be a single expression. (in this case, you would use any)

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

Then move that definition directly into the if not condition:

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

Now it is pretty straight forward to convert:

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

Solution 2:

Are you looking for something like this?:

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

Post a Comment for "Convert A For Loop To A List Comprehension"