How to print an array in the form of key-value pairs in python?

I have a collection of arrays such as

 a = [array([0, 1, 2, 3, 4]) array([0, 1, 2, 3]) array([0, 1, 2, 3, 4])
     array([0, 1, 2, 3, 4, 5, 6, 7, 8]) array([0, 2, 3, 4, 5, 8, 9])

Is there any way to show this result is the form of key-value pairs like

[[(0),(1,2,3,4)],[(1),(0,2,3)],[(2),(0,1,3,4)],[(3),(0,1,2,4,5,6,7,8)]
[(4),(0,2,3,5,8,9)]]

i will get increment by 1 in the key and that value will be not included in the values list


I tried like this, but not able to put it into the required form.

c = [id for id in b if id != i] for i, b in enumerate(a)]

2 answers

  • answered 2018-03-11 13:37 jpp

    List comprehension with enumerate is one way. Note the comma after each single-item key. This represents that the object type is a tuple of length 1.

    from numpy import array
    
    a = [array([0, 1, 2, 3, 4]), array([0, 1, 2, 3]), array([0, 1, 2, 3, 4]),
         array([0, 1, 2, 3, 4, 5, 6, 7, 8]), array([0, 2, 3, 4, 5, 8, 9])]
    
    res = [[(i,), tuple(j for j in arr if j != i)] for i, arr in enumerate(a)]
    
    # [[(0,), (1, 2, 3, 4)],
    #  [(1,), (0, 2, 3)],
    #  [(2,), (0, 1, 3, 4)],
    #  [(3,), (0, 1, 2, 4, 5, 6, 7, 8)],
    #  [(4,), (0, 2, 3, 4, 8, 9)]]
    

    Alternatively, you can create a dictionary:

    res_dict = {i: tuple(j for j in arr if j != i) for i, arr in enumerate(a)}
    
    # {0: (1, 2, 3, 4),
    #  1: (0, 2, 3),
    #  2: (0, 1, 3, 4),
    #  3: (0, 1, 2, 4, 5, 6, 7, 8),
    #  4: (0, 2, 3, 4, 8, 9)}
    

  • answered 2018-03-11 22:52 Aaditya Ura

    You can try numpy approach:

    import numpy as np
    
    a = [np.array([0, 1, 2, 3, 4]),np.array([0, 1, 2, 3]),np.array([0, 1, 2, 3, 4]),
         np.array([0, 1, 2, 3, 4, 5, 6, 7, 8]), np.array([0, 2, 3, 4, 5, 8, 9])]
    
    print([[(i,),tuple(np.delete(j,np.argwhere(j==i)))] for i,j in enumerate(a)])
    

    output:

    [[(0,), (1, 2, 3, 4)], [(1,), (0, 2, 3)], [(2,), (0, 1, 3, 4)], [(3,), (0, 1, 2, 4, 5, 6, 7, 8)], [(4,), (0, 2, 3, 5, 8, 9)]]