简体   繁体   中英

How to print a numpy array as a string of the format (1 2) (3 4) (5 6)?

I have a numpy array such as follows:

[[181  2]
 [  3 45]
 [  5  6]]

However, I'm required to print it as this new format:

(181 2) (3 45) (5 6)

I have tried:

' '.join(map(str, my_arr)).replace('[','(').replace(']',')')

However, due to the whitespace in the original numpy array, the map includes this whitespace so that my result is:

(181  2) (  3 45) (  5  6)

Which includes the original whitespace. Unfortunately, this is an unacceptable format for my purposes, but I cannot figure out a solution.

I have also tried flattening the array first and then converting it to a string of numbers of the following format:

181 2 3 45 5 6

But, from here I wouldn't know how to insert ( and ) characters for every pair of numbers to get the required format above?

尝试这个

' '.join(map(lambda row : '(' + ' '.join(map(str, row)) + ')', my_arr))

One solution. But you should consider whether you really need to perform this kind of manipulation of numeric data.

import numpy as np

arr = np.array([[181,  2],
                [  3, 45],
                [  5,  6]])

print(''.join('('+' '.join(map(str, i))+') ' for i in arr))

# (181 2) (3 45) (5 6) 

One more for the collection:

>>> from itertools import starmap
>>> a = np.arange(6).reshape(3, 2)
>>> ' '.join(starmap(' '.join(a.shape[1] * ['{}']).join('()').format, a))
'(0 1) (2 3) (4 5)'

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