How to match two arrays

前端 未结 3 693
天命终不由人
天命终不由人 2021-01-26 11:51

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 b

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-26 12:19

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

提交回复
热议问题