简体   繁体   English

我想制作一个 numpy 数组

[英]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.

相关问题 在 numpy 数组(元组列表)中,通过多次扩展 () 处理速度变慢。 我想让那部分更快 - In a numpy array (a list of tuples), the processing speed is slow by extending () many times. I want to make that part faster 我想在一个 numpy 数组中返回一个随机序列? - I want to return a random sequence in a numpy array? 我想将.csv 文件转换为 Numpy 数组 - I want to convert .csv file to a Numpy array 给定一个 numpy 整数数组,我想在该数组中返回一个随机序列吗? - Given a numpy array of integers, I want to return a random sequence in that array? 我可以使 Numpy 阵列不可变吗? - Can I make a Numpy array immutable? 为什么我可以在 numpy 阵列中多次执行“[:]”? - Why can I do “[:]” in a numpy array as many times as I want? 我想根据子数组的长度对我拥有的 NumPy 数组中的子数组进行排序 - I want to sort the subarrays in a NumPy array that I have according to their length numpy合并两个数组我可以像这样制作一个numpy数组吗? - Numpy merge two arrays can i make a numpy array like this? 我想将噪声应用于3D numpy数组所描绘的体积 - I want to apply noise to a volume that is depicted by a 3D numpy array 我有一个分类的 numpy 数组,想把它转换成整数吗? - I have a categorical numpy array , want to convert it into integer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM