如何分解这个列表推导式,或者换句话说,如何合并列表中的子集?



我遵循了一些技巧,但仍然不能分解这个列表理解,这在中间列表中意味着什么?它主要用于合并列表中的一些子集,例如

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

因为'员工:张三''实习员工:张三'的子集,所以结果将去掉'员工:张三'

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

我知道外在可能会喜欢,但内在呢?

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)

或者其他实现这个函数的方法?

可以分解为:

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

这里使用了两个Python容易引起误解的结构:

  • word in other != word的链式比较,即word in other and other != word
  • for..else,其中else只在循环不是broken,错误,break没有被调用时才会被执行

或者你也可以这样做:

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)

下面是基于标准循环的等效代码:

l1_res = []
for word in l1:
tmp = []
for other in l1:
tmp.append(word in other != word)
if not any(tmp):
l1_res.append(word)
print(l1_res)
l1 = ['a', 'ab','c','abc']
l1_res = []
for word in l1:
tmp = []
for other in l1:
tmp.append( word in other and other != word)  # word in other != word
if not any(tmp):
l1_res.append(word)
print(l1_res)

相关内容

  • 没有找到相关文章