简体   繁体   English

将 numpy 转换为字符串时空格数不均

[英]Uneven number of spaces when converting numpy to string

I want to convert a numpy array to a string representation and I am having issues when the number of digits in the numpy array is not constant.我想将 numpy 数组转换为字符串表示形式,并且当 numpy 数组中的位数不恒定时出现问题。 Consider the two cases -考虑两种情况——

import numpy as np

arr = np.array([0,0])
arr_str = str(arr).strip("[]")
print("String:", arr_str)
print("Len:", len(arr_str))

arr = np.array([10,0])
arr_str = str(arr).strip("[]")
print("String:", arr_str)
print("Len:", len(arr_str))
 

The output from this is - output 是 -

String: 0 0
Len: 3
String: 10  0
Len: 5

The first case has the two digits separated by a single space while the second one has two spaces.第一种情况有两个数字用一个空格分隔,而第二种情况有两个空格。 The length of the second string should have been 4 and not 5 if it wasn't for the extra space.如果不是因为额外的空间,第二个字符串的长度应该是 4 而不是 5。 Is there any way to convert numpy to string so that every element is consistently separated by a single space?有没有办法将 numpy 转换为字符串,以便每个元素始终由一个空格分隔?

This was with python 3.8 and numpy 1.19.2这是python 3.8numpy 1.19.2

You've done most of the work already.你已经完成了大部分工作。 Now simply split the string and re- join it with single spaces:现在只需split字符串并用单个空格重新join它:

num_list = arr_string.split()
print(' '.join(num_list))

I am confused.我很困惑。 Numpy is consistently separating them. Numpy 始终将它们分开。 Numpy identified that your data consisted of two digit data. Numpy 确定您的数据由两位数数据组成。 As such, it provided two characters of space for every entry.因此,它为每个条目提供了两个字符的空格。 How else would you have wanted numpy to do it?您还希望 numpy 怎么做呢? Take for example,举个例子,

x = np.array([[10,0],[20,30]])

Would you want the first row to be 4 characters and the second to be 5 characters?您希望第一行是 4 个字符,第二行是 5 个字符吗? That would look quite strange.那看起来会很奇怪。

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

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