Skip to content
Advertisement

How to decompose this list comprehension or in other word, how to merge subsets in a list?

I follow some tips but still cannot decompose this list comprehension, what this mean in the middle list? It is mainly for merging some subsets in a list, for example

l1 = ['员工:张三', '实习员工:张三', '职员:李四']

because '员工:张三' is the subset of '实习员工:张三', the reuslt will remove '员工:张三'

l1_res = [word for word in l1 if not any(word in other != word for other in l1)]

I know the outer may like, but what about inner?

l1_res = []
for word in l1:
    if not any(word in other!=word for other in l1): #how to decompose this line?
         l1_res.append(word)

Or anyother way to implement this function?

Advertisement

Answer

This can be decomposed to:

l1_res = []
for word in l1:
    for other in l1:
        if word in other != word:
            break
    else:
         l1_res.append(word)

This uses two of Python’s easily misleading constructs:

  • chained comparison for word in other != word, meaning word in other and other != word
  • for..else, where the else will be executed only if the loop wasn’t broken, err, break wasn’t invoked

Alternatively you can also do:

l1_res = []
for word in l1:
    found = False
    for other in l1:
        if word in other != word:
            found = True
            break
    if not found:
         l1_res.append(word)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement