使用列表列表过滤列表列表

时间:2019-04-03 20:55:39

标签: python python-3.x list list-comprehension

我有两个列表列表,一个包含所有记录,例如[['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]和包含规则[['milk', 'eggs'], ['milk','ham']]的规则。

我正在尝试通过list_of_rules过滤记录,但是,我想捕获[['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']],尽管它与[['milk', 'eggs'], ['milk','ham']]的顺序不完全匹配,并且不明智。

records = [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]

list_of_rules = [['milk', 'eggs'], ['milk','ham']]

# this list comprehension only filters for exact matches

results = [[x for x in L if x in records] for L in list_of_rules] 


# expected output

print(results)
>>[['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']]

任何人和所有建议都非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用此列表理解:

records = [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]

list_of_rules = [['milk', 'eggs'], ['milk','ham']]

results = [L for L in records if any(set(R).issubset(L) for R in list_of_rules)]

print(results) # => [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']]

它为记录L的每个列表循环,并检查是否存在至少一个规则列表R(使用内置函数any),以使{{1} }包含在R中(使用设置方法issubset)。

答案 1 :(得分:0)

您可以使用list条规则中的sets,并要求带有内部列表的任何规则intersectionset相同(即集合中的所有项也都位于内部列表中):

records = [['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk'], ['cereal', 'skittles']]

list_of_rules = [{'milk', 'eggs'}, {'milk','ham'}]

# this list comprehension only filters for exact matches

# take the full inner list if all things in any rule are in this inner list
results = [ x for x in records if any( p.intersection(x) == p for p in list_of_rules)  
print(results)

输出:

[['eggs', 'milk', 'butter'], ['ham', 'spam', 'milk']]