Python:按规则比较列表

时间:2011-12-24 08:29:42

标签: python algorithm

输入数据:

rules = (
    ("1|1": "A"),
    ("2|1": "B"),
    ("3|1": "C"),
    ("2|2": "X")
)

pattern = [[1,2,3], [7,8]]

我需要一个函数来完成以下结果的工作:

list1 = [[1,3,4], [7,9]] # result: B
list2 = [[1,2,3], [7,9]] # result: C
list3 = [[0,5,4], [8,5]] # result: None
list4 = [[1,6,2], [7,8]] # result: X
list5 = [[1,6,2,5], [7,8]] # result: Error

1 个答案:

答案 0 :(得分:3)

一些功能性的Python:

>>> rules = {
    "1|1": "A",
    "2|1": "B",
    "3|1": "C",
    "2|2": "X"
}
>>> pattern = [[1,2,3], [7,8]]
>>> l = [[1,3,4], [7,9]]
>>> diffs = '|'.join(map(lambda x: str(len(set(x[0]) & set(x[1]))),
                         zip(pattern, l)))
>>> rules.get(diffs)
'B'

对其余列表使用相同的内容。错误处理是你的行为:)