I am trying to extract the values from a numpy array and place the individual entries into a list.
For example, if I have the following list:
import numpy as np
x = 1
problem_variable = np.array(['a', 'b'], dtype='<U9')
z = 2
mylist = [x, problem_variable , z]
# [1, array(['a', 'b'], dtype='<U9'), 2]
How do I get the result
[1, 'a', 'b', 2]
I do not know the length of problem_variable
before hand so cannot hard code problem_variable[0]
, problem_variable[1]
etc.
The following does what I want but I am sure that I am missing the appropriate way to break the array apart. Thanks.
result = []
result.append(x)
for i in problem_variable: result.append(i)
result.append(z)
你可以解压你的数组:
mylist = [x, *problem_variable , z]
Since you're using numpy
: you can use np.r_
to concatenate the input objects along first axis:
np.r_[x, problem_variable, z]
# array(['1', 'a', 'b', '2'], dtype='<U9')
Comparing performance on larger lists:
problem_var = np.concatenate([problem_variable]*10000, axis=0)
%timeit np.r_[x, problem_var, z]
# 143 µs ± 19.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit np.hstack((x, problem_var , z))
# 553 µs ± 55.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit [x, *problem_var.tolist() , z]
# 502 µs ± 42.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit [x, *problem_var , z]
# 6.46 ms ± 215 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
You can use np.hstack , which can stack arrays in sequence horizontally,
np.hstack((x, problem_variable , z))
# ['1' 'a' 'b' '2']
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.