简体   繁体   English

如何删除 output 中的多余空间?

[英]how can i remove the extra space in my output?

I'm using the following code to get the mean of an array made with user input.我正在使用以下代码来获取使用用户输入生成的数组的平均值。

import numpy as np

n, p = [int(x) for x in input().split()] n, p = [int(x) for x in input().split()]

lst = [] lst = []

d = (n*p)/2 d = (n*p)/2

for i in range(int(d)):对于我在范围内(int(d)):

ele = input().split()

lst.append(ele)
if len(lst) == (d):
    break

x_arr = np.array(lst) x_arr = np.array(lst)

x_arr.reshape(n, p) x_arr.reshape(n, p)

x_arr_new = x_arr.astype(float) x_arr_new = x_arr.astype(float)

y = x_arr_new.mean(axis=1) print(y) y = x_arr_new.mean(axis=1) print(y)

for example i Input this:例如我输入这个:

3 2 3 2

1 2 1 2

1 0.5 1 0.5

1 0.3 1 0.3

the OUTPUT that i have is this:我拥有的 OUTPUT 是这样的:

[1.5 0.75 0.65]

while the OUTPUT that i want is this:而我想要的 OUTPUT 是这样的:

[1.5 0.75 0.65]

Notice the difference in spaces between the first and second OUTPUT after the first number注意第一个数字后的第一个和第二个 OUTPUT 之间的空格差异

Use just have to create custom string object instead of calling inbuilt numpy __str__ method return string object.使用只需创建custom string object而不是调用内置numpy __str__方法返回字符串 object。 For that use have to add this line of code:为此,必须添加这行代码:

y = [str(i) for i in y]

FINAL CODE

import numpy as np
n, p = [int(x) for x in input().split()]
lst = []
d = (n*p)/2
for i in range(int(d)):
    ele = input().split()
    lst.append(ele)

x_arr = np.array(lst)
x_arr.reshape(n, p)
x_arr_new = x_arr.astype(float)
y = x_arr_new.mean(axis=1) 
y = [str(i) for i in y]
print(' '.join(y))

as I wanted the answer to be in the form of a list without two spaces after the first number, I did the following因为我希望答案是在第一个数字后没有两个空格的列表形式,所以我做了以下

import numpy as np

n, p = [int(x) for x in input().split()]

lst = []

d = (n*p)/2

for i in range(int(d)):
    ele = input().split()
    lst.append(ele)
    if len(lst) == (d):
        break

x_arr = np.array(lst)

x_arr.reshape(n, p)

x_arr_new = x_arr.astype(float)

y = x_arr_new.mean(axis=1)

k = []

for t in y:
   k.append(t)

k_arr = np.array(str(k))

b = ''.join(str(k).split(','))

print(b)

the input will be输入将是

3 2 3 2

1 3 1 3

1 0.5 1 0.5

=========== ============

the OUTPUT will be OUTPUT 将是

[2.0 0.65 0.75] [2.0 0.65 0.75]

without any space没有任何空间

of course I'm a beginner so forgive me for the crude code当然我是初学者所以请原谅我的粗略代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM