如何将NumPy代码输出的逗号分隔元素转换为列表格式
Got it, let's fix that output format for you! The original code prints elements separated by commas, but we need to wrap them in brackets to match the list-style output you want. Here are a couple of straightforward ways to do this:
Approach 1: Convert NumPy Array to Python List (Simplest)
The easiest method is to convert your NumPy array j into a regular Python list using tolist(). When you print a Python list directly, it automatically uses the [element1, element2] format you're looking for:
import numpy as np array = np.array([1,3,4,9,3,4,5,0,1]) lmax = (array[1:-1] > array[2:]) & (array[1:-1] > array[:-2]) j = np.arange(1, array.size-1)[lmax] print(j.tolist()) # Modified line
Running this will output exactly [3,6].
Approach 2: Manual String Formatting (For Customization)
If you want more control over the output string, you can construct it manually by joining the elements and wrapping them in brackets:
import numpy as np array = np.array([1,3,4,9,3,4,5,0,1]) lmax = (array[1:-1] > array[2:]) & (array[1:-1] > array[:-2]) j = np.arange(1, array.size-1)[lmax] print(f"[{','.join(map(str, j))}]") # Modified line
This converts each element in j to a string, joins them with commas, and adds surrounding brackets to achieve the desired output.
内容的提问来源于stack exchange,提问作者nishank

