[英]I want to make a numpy array
As the title says I want to make a numpy array.正如标题所说,我想制作一个 numpy 数组。
array=np.random.randint(2,size=(4,4))
First question, at this time I want to make code that size can be changeable.第一个问题,此时我想制作大小可以更改的代码。 What should I do?
我该怎么办?
top = input("Top(k):")
Second question, I want to receive k value like this and send output as much as this value.第二个问题,我想接收这样的 k 值并发送与该值一样多的输出。 At this time, I wanna print the top k-row indexes from the weakest to the strongest (weakest:smaller number of ones) How to do it??:(
这时候,我想从最弱到最强(最弱:数量较少)打印前k行索引怎么做??:(
example like this.像这样的例子。
input输入
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]]
Top(k):2顶部(k):2
output输出
0,2
0,2
if Top(k):4, output is如果 Top(k):4,则输出为
0,2,3,1
0,2,3,1
Numpy uses static arrays (it is implemented in C), you cannot change the size of a numpy array as you would with python lists. Numpy 使用静态数组(它是用 C 实现的),您不能像使用 python 列表那样更改 numpy 数组的大小。 However, you can use the
numpy.ndarray
constructor to create a numpy array from python list: array = numpy.ndarray(my_python_array)
.但是,您可以使用
numpy.ndarray
构造函数从 python 列表创建一个 numpy 数组: array = numpy.ndarray(my_python_array)
。
For you second answer you can use the function sum()
of ndarray and use it like this:对于您的第二个答案,您可以使用 ndarray 的函数
sum()
并像这样使用它:
histogram = []
for i in range(len(array_2D)):
# Store the row indexes as well as number of ones
histogram.append((i, array2D[i].sum()))
# Sort regarding the number of ones
histogram.sort(key=lambda e:e[1])
for index, val in histogram[:k]:
print(index, end=" ")
Here array2D is the numpy array you got from user input.这里 array2D 是您从用户输入中获得的 numpy 数组。 You should parse the user input to get a numpy array before executing this code.
在执行此代码之前,您应该解析用户输入以获取一个 numpy 数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.