如何匹配两个数组

0 投票
3 回答
1882 浏览
提问于 2025-04-16 12:05

我有两个数组

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

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或者库的时候。这些问题可能会让我们感到困惑,不知道该怎么解决。比如,有人可能在使用某个功能时,发现它并没有按照预期工作,这时候就需要去查找原因。

通常,我们可以通过查看文档、搜索网上的资料或者向其他开发者请教来找到解决方案。有时候,问题可能是因为我们没有正确理解某个概念,或者是因为代码中有小错误。

总之,遇到问题是学习编程过程中很正常的一部分,重要的是要保持耐心,积极寻找解决办法。

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)
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

在优雅的Python代码中:

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

撰写回答