简体   繁体   中英

Format output in python

I have the following function which transforms list of numbers:

import numpy as np
from math import *


def walsh_transform(x):
    if len(x) > 3:
        n = len(x)
        m = trunc(log(n, 2))
        x = x[0:2 ** m]
        h2 = [[1, 1], [1, -1]]
        for i in range(m - 1):
            if i == 0:
                h = np.kron(h2, h2)
            else:
                h = np.kron(h, h2)

        return np.dot(h, x) / 2. ** m

arr = [1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0]

print(walsh_transform(arr))

It returns output [ 0.625 -0.125 -0.125 0.125 0.625 -0.125 -0.125 0.125]

How can I make it return output [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125] ? Ie comma-separated values?

只需将最终结果转换为列表,因为列表以您想要的格式打印出来。

print(list(walsh_transform(arr)))

您可以return [z for z in np.dot(h, x) / 2. ** m]使用return [z for z in np.dot(h, x) / 2. ** m]而不是return np.dot(h, x) / 2. ** m

You can convert the resultant array to list to get a output as you wanted.

w = walsh_transform(arr) # w = [ 0.625 -0.125 -0.125  0.125  0.625 -0.125 -0.125  0.125]

print(list(w)) # output = [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125]

Try using repr

print(repr(walsh_transform(arr))) # output = [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125]

Alternatively, you can cast it to a list:

print(list(walsh_transform(arr))) # output = [0.625, -0.125, -0.125, 0.125, 0.625, -0.125, -0.125, 0.125]

All you have to do is replace the whitespace with commas.

re.sub function should work too.

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