Python List Indexed by Tuples

I am a Matlab user who should use Python for some things, I would really appreciate it if someone could help me with the Python syntax:

(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use this to represent a data matrix.

(2) Assuming I can use a list indexed by tuples, say data [(row, col)], how do I delete the entire column? I know in matlab, I can do something like

 new_data = [data(:,1:x-1) data(:,x+1:end)];

if i need to remove column x from data.

(3) How can I easily count the number of non-negative elements in each row. For example, in Matlab, I can do something like this:

 sum(data>=0,1)

this will give me a column vector that represents the number of non-negative entries in each row.

Thanks a lot!

+3
source share
7 answers

I agree with everyone. Use Numpy / Scipy. But here are the specific answers to your questions.

  • Yes. And the index can be either an inline list or a Numpy array. Suppose x = scipy.array([10, 11, 12, 13])and y = scipy.array([0, 2]). Then x[[0, 2]]they x[y]return the same thing.

  • new_data = scipy.delete(data, x, axis=0)

  • (data>=0).sum(axis=1)

: 2 Numpy/Scipy. 3, axis 0 , 1 .. , delete, , 2. , major major major.

+2
+8
  • , dicts can.
  • , "2d-", - . numpy?
  • , # 2, Python sum , . gen-exprs ( ) . :
row_count_of_non_neg = sum(1 for n in row if n >= 0)
# or:
row_count_of_non_neg = sum(n >= 0 for n in row)
# "abusing" True == 1 and False == 0
+3

, () numpy:

>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])

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

:

>>> a[0,:]
array([1, 2, 3])
>>> a[:,0]
array([1, 4, 7])

, ! Numpy .

+2

, , __getitem__ __setitem__ . :

class my_list(list):
    def __getitem__(self, key):
        if isinstance(key, tuple) and len(key) > 0:
            temp = []
            for k in key: temp.append(list.__getitem__(self, k))
            return temp
        else:
            return list.__getitem__(self, key)

    def __setitem__(self, key, data):
        if isinstance(key, tuple) and len(key) > 0:
            for k in key: list.__setitem__(self, k, data)
        else:
            list.__setitem__(self, key, data)


if __name__ == '__main__':
   L = my_list([1, 2, 3, 4, 5])
   T = (1,3)
   print(L[T]) 
+1

(1) , python. (, [i] [j]), , , . , .

d = { (1,1):1, (2,1):2  ... } 

(2) ,

map( lambda x: d.remove(x) if x[1] = col_number, d.keys() )

(3) .

sum(
map( lambda x:x[1], filter(lambda x,y: x[1] == row_num and y > 0, d.items()))
)
0

, , , . - . - -, -. . , , , . , , . , , , , .

, , . .

0

Source: https://habr.com/ru/post/1729167/


All Articles