Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form

hongy...@gmail.com hongyi.zhao at gmail.com
Mon May 16 19:11:13 EDT 2022


On Monday, May 16, 2022 at 11:27:58 PM UTC+8, Dennis Lee Bieber wrote:
> On Mon, 16 May 2022 02:03:26 -0700 (PDT), "hongy... at gmail.com" 
> <hongy... at gmail.com> declaimed the following: 
> 
> 
> >print(lst) 
> 
> Printing higher level structures uses the repr() of the structure and 
> its contents -- theoretically a form that could be used within code as a 
> literal. If you want human-readable str() you will need to write your own 
> output loop to do the formatting of the structure, and explicitly print 
> each item of the structure.

Thank you for your explanation. I have come up with the following methods:
```
b=[[0.0, -1.0, 0.0, 0.25], [1.0, 0.0, 0.0, 0.25], [0.0, 0.0, 1.0, 0.25], [0.0, 0.0, 0.0, 1.0]]
import numpy as np
from fractions import Fraction
import re

def strmat(m):
    if(np.array([m]).ndim==1):
        return str(Fraction(m))
    else: return list(map(lambda L:strmat(L), np.array(m)))

a=str(strmat(b))
a=re.sub(r"'","",a)
repr(a)
print(repr(a))
'[[0, -1, 0, 1/4], [1, 0, 0, 1/4], [0, 0, 1, 1/4], [0, 0, 0, 1]]'
```
Best, 
HZ


More information about the Python-list mailing list