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
JavaScript
x
2
1
l1 = ['员工:张三', '实习员工:张三', '职员:李四']
2
because '员工:张三'
is the subset of '实习员工:张三'
, the reuslt will remove '员工:张三'
JavaScript
1
2
1
l1_res = [word for word in l1 if not any(word in other != word for other in l1)]
2
I know the outer may like, but what about inner?
JavaScript
1
5
1
l1_res = []
2
for word in l1:
3
if not any(word in other!=word for other in l1): #how to decompose this line?
4
l1_res.append(word)
5
Or anyother way to implement this function?
Advertisement
Answer
This can be decomposed to:
JavaScript
1
8
1
l1_res = []
2
for word in l1:
3
for other in l1:
4
if word in other != word:
5
break
6
else:
7
l1_res.append(word)
8
This uses two of Python’s easily misleading constructs:
- chained comparison for
word in other != word
, meaningword in other and other != word
for..else
, where theelse
will be executed only if the loop wasn’tbroken
, err,break
wasn’t invoked
Alternatively you can also do:
JavaScript
1
10
10
1
l1_res = []
2
for word in l1:
3
found = False
4
for other in l1:
5
if word in other != word:
6
found = True
7
break
8
if not found:
9
l1_res.append(word)
10