如何匹配两个数组

时间:2011-02-18 17:26:41

标签: python ironpython

我有两个数组

A = [a, b, c, d]

B = [a1, a2, b1, b2, b3, c1, c2, c3, d1, d2, d3, d4]

我想在两个数组之间进行匹配。

匹配结果:

[a : a1, a2]
[b : b1, b2, b3]
[c : c1, c2, c3]
[d : d1, d2, d3, d4]

3 个答案:

答案 0 :(得分:2)

在漂亮的Python中:

di = {}
for item in A:
    di[item] = filter(lambda v: v.startswith(item), B)

答案 1 :(得分:1)

这些解决方案在pythonIronPython中均可正常使用。

势在必行的解决方案:

A = ["a", "b", "c", "d"]
B = ["a1", "a2", "b1", "b2", "b3", "c1", "c2", "c3", "d1", "d2", "d3", "d4"]

results = []

for prefix in A:
    matches = []
    results.append((prefix, matches))
    for el in B:
        if el.startswith(prefix):
            matches.append(el)

for res in results:
    print res

功能解决方案:

A = ["a", "b", "c", "d"]
B = ["a1", "a2", "b1", "b2", "b3", "c1", "c2", "c3", "d1", "d2", "d3", "d4"]

groups = [(x,[y for y in B if y.startswith(x)]) for x in A]
for group in groups:
    print group

<强>结果:

('a', ['a1', 'a2'])
('b', ['b1', 'b2', 'b3'])
('c', ['c1', 'c2', 'c3'])
('d', ['d1', 'd2', 'd3', 'd4'])

答案 2 :(得分:0)

from collections import defaultdict

A = ["a", "b", "c", "d"]
B = ["a1", "a2", "b1", "b2", "b3", "c1", "c2", "c3", "d1", "d2", "d3", "d4"]
d = defaultdict(list)
for item in B:
    prefix = item[0]
    if prefix in A:
        d[prefix].append(item)