简体   繁体   中英

python single element tuple

Suppose I have a matrix M and an indexing set idx=[(0,1),(2,3),(3,2)] and I want to create two sets of tuples, idx_leq1 consisting of those tuples whose first and second elements are both less than or equal to 1 and idx_geq2 consisting of those tuples whose first and second elements are both greater than or equal to 2.

I want to access the elements M[idx_leq1] and M[idx_geq2] cleanly. I have tried idx_leq1 = tuple([e for e in idx if e[0]<=1 and e[1]<=1]) , but this returns idx_leq1 = ((0,1),) which I can't use to index M . On the other hand, idx_geq2 = tuple([e for e in idx if e[0]>=2 and e[1]>=2]) = ((2,3),(3,2)) works.

How can I solve this for the case where my first index set consists of only one coordinate pair? I don't want to do M[idx_leq1[0]] .

I can do: list(chain(*[(e,) for e in idx if e[0]<=1 and e[1]<=1])) and list(chain(*[(e,) for e in idx if e[0]>=2 and e[1]>=2])) , but then I still have to grab the first element for idx_leq1 whereas I can pass idx_geq2 to M and grab the appropriate elements.

Thanks!

[Tested with numpy.mat ]

[M[0, 1]] should be fetched as in M[[0], [1]] . When indexing matrix, Multidimensional list-of-locations indexing requires k lists of index each working with one dimension.

For example, in order to fetch M[0, 3], M[1, 4], M[2, 5] , one should use M[[0, 1, 2], [3, 4, 5]] . In other word, the index that you give to M should not be considered lists of coordinates. Rather, they are lists of "coordinates on each dimension".
In your case, a M[[0, 1]] (or its equivalent in tuple type) fetches M[0], M[1] as [0, 1] is considered to work on the first dimension, and the second dimension is broadcasted.

Ref: http://scipy-cookbook.readthedocs.io/items/Indexing.html#Multidimensional-list-of-locations-indexing
This reference believes that the reason to use "list of dims" rather than "list of coordinates" is to save number of instances, as unpacking many tuples might be expensive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM