Yesterday I needed a matrix type in Python.
Apparently, the trivial answer to this need would be to use numpy.matrix() , but the additional problem I have is that I would like the matrix to keep arbitrary values ββwith mixed types, similar to a list. numpy.matrix does not do this. Example:
>>> numpy.matrix([[1,2,3],[4,"5",6]]) matrix([['1', '2', '3'], ['4', '5', '6']], dtype='|S4') >>> numpy.matrix([[1,2,3],[4,5,6]]) matrix([[1, 2, 3], [4, 5, 6]])
As you can see, numpy.matrix should be uniform in content. If a string value is present in my initialization, each value is implicitly stored as a string. This is also confirmed by accessing single values.
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1] '5' >>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2] '6'
Python list type can now accept mixed types. You can have a list containing an integer and a string, storing their type. What I need is something like a list, but working as a matrix.
So I had to implement my own type. I had two options for internal implementation: a list containing lists, and dictionaries. Both solutions have disadvantages:
- list of lists requires careful synchronization of the sizes of different lists. Switching between two lines is easy. Changing two columns is less simple. Deleting a row is also easy. Dictionary
- (with a tuple as a key) is slightly better, but you must determine the limits of your key (for example, you cannot insert a 5.5 element if your matrix is ββ3x3), and they are more difficult to use to insert, delete or replace columns or rows.
Edit: clarification. The specific reason why I need this functionality is because I am reading CSV files. As soon as I collect values ββfrom a CSV file (values ββthat can be strings, integers, floats), I would like to perform swap, delete, insert, and other operations. For this reason, I need a "matrix list".
My curiosities:
- Do you know if there is a Python data type that provides this service (possibly in a battery-free library)?
- Why is this data type not specified in the standard library? Too limited interest maybe?
- How would you solve this problem? A dictionary, list, or other smarter solution?