Akshay Kumbharkar
Akshay Kumbharkar

Reputation: 47

How to get subset of string within same list

I have one list

a = ['find old', 'find old mails', 'finding', 'find your pc', 'find your pc s ip', 'find your pc s ip address']

i want to remove SUBSET STRING from list which will give me result as

['find old mails', 'finding', 'find your pc s ip address'] 

Test Code

a = ['find old', 'find old mails', 'finding', 'find your pc', 'find your pc s ip', 'find your pc s ip address']
b = len(a)
def is_sub(sub, lst):
    ln = len(sub)
    return any(lst[i: i + ln] == sub for i in range(len(sub) - ln + 1))

# print(is_sub(a[0],a[2]))
for i in range(b-1):
    for j in range(i+1,b):
        if is_sub(a[i],a[j]):
            index = a.index(a[i])
            a.remove(a[index])
            break
    b = len(a)

print(a)

I am getting output as

['find old mails', 'finding', 'find your pc s ip', 'find your pc s ip address']

and expected output

['find old mails', 'finding', 'find your pc s ip address']

Upvotes: 0

Views: 495

Answers (2)

Saharsh
Saharsh

Reputation: 1098

Why not use in keyword?

a = ['find old', 'find old mails', 'finding', 'find your pc', 'find your pc s ip', 'find your pc s ip address']
new = []
f = 0
for i in range(0,len(a)):
    f=0
    for j in range(0, len(a)):
        if a[i] in a[j] and not i==j:
            f=1
            break;
    if f==0: new.append(a[i])
print(new)

This gives -

['find old mails', 'finding', 'find your pc s ip address']

Upvotes: 0

metasomite
metasomite

Reputation: 140

By making a few alterations to your substring checking function (specifically using in to check for substrings) and using a list comprehension, you can achieve the desired result:

def is_sub(item, lst):
    """Check whether an item is a substring of other items in a list."""
    return any([item in i for i in [i for i in lst if i != item]])

output = [i for i in a if not is_sub(i, a)]
['find old mails', 'finding', 'find your pc s ip address']

Upvotes: 1

Related Questions