ten*_*nac 6 python filter nested-lists
我想用另一个可变长度的列表过滤嵌套列表.如果子列表中的任何项与筛选器列表的任何元素匹配,则应排除子列表.以下代码对我有用,但是这个任务有一个"更清洁"的解决方案吗?
the_list = [['blue'], ['blue', 'red', 'black'], ['green', 'yellow'], ['yellow', 'green'], ['orange'], ['white', 'gray']]
filters = ['blue', 'white']
filtered_list = []
for sublist in the_list:
for item in sublist:
if item in filters:
break
filtered_list.append(sublist)
break
Run Code Online (Sandbox Code Playgroud)
预期产量:
filtered_list = [['green', 'yellow'], ['yellow', 'green'], ['orange']]
Run Code Online (Sandbox Code Playgroud)
也许使用any
.
for sublist in the_list:
if any(item in filters_exclude for item in sublist):
continue
filtered_list.append(sublist)
Run Code Online (Sandbox Code Playgroud)
也许矫枉过正,但您甚至可以将其考虑到自己的功能中,然后使用内置 filter
def good_list(some_list):
return not any(item in filters_exclude for item in some_list)
filtered_list = filter(good_list, the_list)
Run Code Online (Sandbox Code Playgroud)
这应该可以实现您描述的目标。但是,您编写的代码存在潜在问题,如注释中的mentioend。