Python - Uniquely determining which text file an element originated from
Question: I'm loading in three separate text files using numpy with the code:

    
    
    str = 'data'
    Di = np.loadtxt(str+'i.txt', dtype=np.float64) 
    Dj = np.loadtxt(str+'j.txt', dtype=np.float64)
    Dk = np.loadtxt(str+'k.txt', dtype=np.float64)
    

The text files contain 2-dimensional data with `2` columns and roughly `6000`
rows (they all contain `2` columns but the number of rows is variable). Given
an element `[a,b]` \- how can i uniquely determine which text file it
originated from?

I can't entirely ensure that the elements are unique though, the number
`[a,b]` may occur in both (for example) the datai and dataj text files -
however it is very unlikely, but I can't rule it out entirely.

Edit:

Loading in the text files, for example, gives:

    
    
    Di = [[1   4]      Dj = [[9   4]        Dk = [[2   4]       
          [1   5]            [5   5]              [5   6]
          [4   5]            [3   6]]             [4   7]]
    
          datai.txt          dataj.txt            datak.txt         
    

So given the element `[1 4]` the output would be `datai.txt`, letting me know
the element `[1 4]` originated from the `datai.txt` file.


Answer: Something like:

    
    
    import numpy
    
    Di = numpy.array([[1, 4], [1, 5], [4, 5]])
    
    Dj = numpy.array([[9, 4], [5, 5], [3, 6]])
    
    Dk = numpy.array([[2, 4], [5, 6], [4, 7]])
    #>>> 
    
    next(array for array in [Di, Dj, Dk] if ([5, 5] == array).all(1).any())
    #>>> array([[9, 4],
    #>>>        [5, 5],
    #>>>        [3, 6]])
    

?

If you want the index:

    
    
    next(i for i, array in enumerate([Di, Dj, Dk]) if ([5, 5] == array).all(1).any())
    #>>> 1
    

or the name:

    
    
    next(k for k, array in {"Di":Di, "Dj":Dj, "Dk":Dk}.items() if ([5, 5] == array).all(1).any())
    #>>> 'Dj'
    

* * *

The

    
    
    ([5, 5] == array).all(1).any()
    

is the key part, it does (using [9, 4] for explanation)

    
    
    [9, 4] == array
    #>>> array([[ True,  True],
    #>>>        [False, False],
    #>>>        [False, False]], dtype=bool)
    

Then you `all` along the axis going across.

    
    
    ([9, 4] == Dj).all(1)
    #>>> array([ True, False, False], dtype=bool)
    

And then you check if any of the axis matched.

* * *

The

    
    
    next(array for array in [Di, Dj, Dk] if CONDITION)
    

makes an iterable that only contains those arrays that satisfy CONDITION,
`next` gets the first.

You can use `next(..., fallback)` if you don't like catching `StopIteration`.

