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!
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.
x = scipy.array([10, 11, 12, 13])
y = scipy.array([0, 2])
x[[0, 2]]
x[y]
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.
axis
delete
numpy, .
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
, () 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 .
, , __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) , 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())) )
, , , . - . - -, -. . , , , . , , . , , , , .
, , . .
Source: https://habr.com/ru/post/1729167/More articles:Automatically resize window contents in WPF - c #Python parallel loop - pythonHow to bind Popup (or ContextMenu) PlacementTarget to an element in UserControl? - wpfLinks below the site on google search - google-searchHow does a C ++ builder stack up against other RAD-IDEs? - c ++ASP.NET MVC ViewModel Console - c #point object reference - c ++is there a way to not stop the script if errors are detected? - phpJQuery backgroundPosition Animation Question - jqueryWhy does C ++ not implement construction + calling functions on a single line? - c ++All Articles