Home>

Thank you for browsing. There is a stumbling block in the Python array, and I would appreciate it if you could teach me.

lst = ['Shiritori. Apple. gorilla. ','Apple. gorilla. ','gorilla. ',' Cat. Dog. Rabbits. ','Rabbits. ']

If there is such an array, I would like to get the shortest element with partial matching of elements in the following array.

lst = ['Gorilla. ','Rabbits. ']

I'm sorry I couldn't explain it well. Thank you.

The problem i am having

I researched it myself and tried to program it, but I couldn't get the result I wanted.
I think there is a problem with the way of thinking and approach.

Corresponding source code

I don't know if it will be helpful, but I will list the source code.
Sorry for the unsightly source code.

lst1 = []
lst2 = ['Shiritori. Apple. gorilla. ','Apple. gorilla. ','gorilla. ',' Cat. Dog. Rabbits. ','Rabbits. ']
lst2.insert (0,'')
for i in range (1, len (lst2) -1):
    if (lst2 [i] not in lst2 [i-1]):
        lst1.append (lst2 [i])
list = set (lst2) --set (lst1)
l = [x for x in list if x]
print (l)
>>['Rabbit. ', 'Apple. gorilla. ',' Gorilla. ']
  • Answer # 1

    What do you want to do?

    lst2 = ['Shiritori. Apple. gorilla. ','Apple. gorilla. ','gorilla. ',' Cat. Dog. Rabbits. ','Rabbits. ']
    lst1 = [s for i, s in enumerate (lst2) for t in lst2 [: i] + lst2 [i + 1:] if s in t]
    lst1 = list (set (lst1))
    lst3 = [s for i, s in enumerate (lst1) for t in lst1 [: i] + lst1 [i + 1:] if t in s]
    for s in lst3:
        lst1.remove (s)
    print (lst1) # ['Gorilla. ','Rabbits. ']

    list = set (lst2) --set (lst1)

    If you use the variable name list, you will not be able to use list as a class, so stop it.
    (You can use it if you del, but it is difficult to understand)
    I also feel that the name of list in the object of set is confusing.

    If you want to extract an element that does not contain other elements
    lst2 = ['Shiritori. Apple. gorilla. ','Apple. gorilla. ','gorilla. ',' Cat. Dog. Rabbits. ','Rabbits. ','bird. monkey. pheasant. ']
    lst1 = lst2.copy ()
    lst3 = [t for i, s in enumerate (lst2) for t in lst1 [: i] + lst1 [i + 1:] if s in t]
    lst3 = list (set (lst3))
    for s in lst3:
        lst1.remove (s)
    print (lst1) # ['Gorilla. ','Rabbits. ','bird. monkey. pheasant. ']