You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中统一numpy数组字符串格式并转换为numpy数组的方法

How to Normalize Numpy Array Strings for Consistent Conversion

To fix the inconsistent spacing inside your array brackets (like the extra spaces after [ and before ] in your second example), you can use regex-based string cleaning—this is robust enough to handle any number of extra spaces, not just single ones. Here's a step-by-step solution:

Step 1: Clean the Array Strings

First, we'll target and remove any spaces immediately following [ or preceding ] using regular expressions. This ensures all your array strings follow the same [x1 x2 x3 ...] format.

Example Code:

import re

# Your original input string
input_str = """[0.46619281 -0.79148525 0.20800316 -0.16633733 1.53767002] 
[ 0.53119281 -0.79148525 0.20800316 -0.16633733 1.53762345 ]"""

# Clean the string: remove spaces after [ and before ]
cleaned_str = re.sub(r'\[\s+', '[', input_str)  # Replace "[   " with "["
cleaned_str = re.sub(r'\s+\]', ']', cleaned_str)  # Replace "   ]" with "]"

print(cleaned_str)

Output:

[0.46619281 -0.79148525 0.20800316 -0.16633733 1.53767002]
[0.53119281 -0.79148525 0.20800316 -0.16633733 1.53762345]

Step 2: Convert Cleaned Strings Back to Numpy Arrays

Now that your strings are standardized, you can easily convert them using methods like numpy.fromstring (as referenced in your post):

import numpy as np

# Split cleaned string into individual array entries
array_strings = cleaned_str.splitlines()

# Convert each string to a numpy array
numpy_arrays = []
for s in array_strings:
    # Extract the numbers inside the brackets and convert
    arr = np.fromstring(s[1:-1], sep=' ')
    numpy_arrays.append(arr)

# Check the result
for idx, arr in enumerate(numpy_arrays):
    print(f"Array {idx+1}: {arr}")

Output:

Array 1: [ 0.46619281 -0.79148525  0.20800316 -0.16633733  1.53767002]
Array 2: [ 0.53119281 -0.79148525  0.20800316 -0.16633733  1.53762345]

Alternative: Non-Regex Cleaning

If you prefer avoiding regex, you can use basic string operations to target the specific spaces:

cleaned_lines = []
for line in input_str.splitlines():
    stripped_line = line.strip()
    # Remove space after [ if present
    if stripped_line.startswith('[ '):
        stripped_line = '[' + stripped_line[2:]
    # Remove space before ] if present
    if stripped_line.endswith(' ]'):
        stripped_line = stripped_line[:-2] + ']'
    cleaned_lines.append(stripped_line)

cleaned_str = '\n'.join(cleaned_lines)

This works for single spaces adjacent to brackets, but regex is better if you might have multiple spaces (e.g., [ 1.0 2.0 ]).

内容的提问来源于stack exchange,提问作者Harry Boy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:02:40