我有两个列表列表,一个包含所有记录,例如[['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']]
任何人和所有建议都非常感谢。
答案 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
,并要求带有内部列表的任何规则intersection与set
相同(即集合中的所有项也都位于内部列表中):
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']]