Home > Net >  How to slice list based on a condition that every element of another list must appear atleast once?
How to slice list based on a condition that every element of another list must appear atleast once?

Time:11-17

I have two lists :

a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0]
key = [1, 2, 4, 6]

I want to check if all elements in the key have atleast once appeared in the list a and remove the ones after that.

desired output :

a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]

here is what i tried:

if a[-1] not in key:
        indx = -1
        while indx < 0:
            
            if a[indx] in k:
                ind = indx
                indx = 1
            else: indx= indx-1
            
        a = a[:ind 1]  

but this just check if the last element of a is in key. Idk how to check for the condition if all the key elements have appeared atleast once. Can some help ?

CodePudding user response:

This function slices the list based on the condition that every element of the key must appear at least once in a.

def slice_list(a, key):
    for i in range(len(a)):  # iterate over the list
        if a[i] in key:  # check if the element is in the key
            key.remove(a[i])  # remove the element from the key
        if not key:  # if the key is empty
            return a[: i   1]  # return the sliced list
    return a  # if the key is not empty return the original list


print(slice_list(a, key))


Output: [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]

CodePudding user response:

Try:

a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0]
key = [1, 2, 4, 6]

max_idx = max(a.index(k) for k in key)
print(a[: max_idx   1])

Prints:

[3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]

CodePudding user response:

Another method to get the same result :)

for i in range(len(a)):
    if all(x in a[:i] for x in key):
        b = a[:i]
        break
print(b)
Output: [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
  • Related