How to match two arrays

谁说胖子不能爱 提交于 2019-12-02 20:55:49

问题


I have two arrays

A = [a, b, c, d]

and

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

I want to match between the two arrays.

Match Result:

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

回答1:


In pretty Python:

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



回答2:


These solutions works fine both in python and IronPython.

Imperative solution:

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

Functional solution:

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

RESULT:

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



回答3:


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)


来源:https://stackoverflow.com/questions/5044491/how-to-match-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!