我想用另一个可变长度的列表过滤嵌套列表。如果子列表中的任何项与筛选器列表的任何元素匹配,则应排除子列表。以下代码适用于我,但有一个"清洁"这项任务的解决方案?
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
预期产出:
filtered_list = [['green', 'yellow'], ['yellow', 'green'], ['orange']]
答案 0 :(得分:3)
使用any
可能会更加语义化。
for sublist in the_list:
if any(item in filters_exclude for item in sublist):
continue
filtered_list.append(sublist)
也许是矫枉过正,但你甚至可以将其纳入自己的功能然后使用内置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)
这应该完成你描述的目标。但是,您编写的代码存在潜在问题,如评论中的mentioend。
答案 1 :(得分:2)
您可以使用filter
和map
将其作为" one-liner"。它没有提高可读性,但它有效:
filters_exclude = [2, 4]
initial_list = [[1, 2, 3, 4], [1, 2, 3], [2, 3, 4, 5]]
final = list(map(lambda x: filter(lambda y: y not in filters_exclude, x), initial_list)
示例:
>>> filters_exclude = [2, 4]
>>> map(lambda x: filter(lambda y: y not in filters_exclude, x), [[1, 2, 3, 4], [1, 2, 3]])
[[1, 3], [1, 3]]
答案 2 :(得分:2)
您可以使用列表理解:
the_list = [['blue'], ['blue', 'red', 'black'], ['green', 'yellow'],['orange'], ['white', 'gray']]
filters = ['blue', 'white']
final_l = [i for i in the_list if not any(b in filters for b in i)]
输出:
[['green', 'yellow'], ['orange']]
或者,使用过滤器:
final_l = filter(lambda x:not any(b in filters for b in x), the_list)
答案 3 :(得分:2)
您可以使用条件列表理解。
>>> [sublist for sublist in the_list
if all(filter not in set(sublist) for filter in filters)]
[['green', 'yellow'], ['orange']]
答案 4 :(得分:2)
您还可以使用filter()
Set intersection
列出与列表filters
没有交集的列表:
>>> the_list = [['blue'], ['blue', 'red', 'black'], ['green', 'yellow'], ['yellow', 'green'], ['orange'], ['white', 'gray']]
>>> filters = ['blue', 'white']
>>> list(filter(lambda x: not set(x).intersection(filters), the_list))
[['green', 'yellow'], ['yellow', 'green'], ['orange']]
或者理解:
>>> [x for x in the_list if not set(x).intersection(filters)]
[['green', 'yellow'], ['yellow', 'green'], ['orange']]
答案 5 :(得分:2)
使用套装。
the_list = map(set, the_list)
filters = set(filters)
fl = []
for sub in the_list:
sub = sub.difference(filters)
if sub:
fl.append(list(sub))
答案 6 :(得分:1)
这与您拥有的非常接近
the_list = [['blue'], ['blue', 'red', 'black'], ['green', 'yellow'],
['yellow', 'green'], ['orange'], ['white', 'gray']]
filters = ['blue', 'white']
filtered_list = []
for sublist in the_list:
sub_filtered_list=[]
for item in sublist:
if item in filters:
continue
else:
sub_filtered_list.extend([item])
if sub_filtered_list==[]:
continue
else:
filtered_list.append(sub_filtered_list)
print(filtered_list)
答案 7 :(得分:0)
filtered_list=[];
for sublist in the_list:
if len(list(set(sublist).intersection(filters_exclude)))>0:
break;
filtered_list.append(sublist);
set(sublist).intersection(filters_exclude)返回两个列表的交集。 List()将该集转换为List。 Len()返回List的长度。