小编Fab*_*bio的帖子

numpy.where(condition)的输出不是一个数组,而是一个数组的元组:为什么?

我正在试验这个numpy.where(condition[, x, y])功能.
numpy文档中,我了解到如果只给出一个数组作为输入,它应该返回数组非零的索引(即"True"):

如果只给出条件,则返回元组condition.nonzero(),条件为True的索引.

但是如果尝试它,它会返回一个包含两个元素的元组,其中第一个是索引的通缉列表,第二个是null元素:

>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9])
>>> np.where(array>4)
(array([4, 5, 6, 7, 8]),) # notice the comma before the last parenthesis
Run Code Online (Sandbox Code Playgroud)

所以问题是:为什么?这种行为的目的是什么?在什么情况下这是有用的?实际上,为了获得所需的索引列表,我必须添加索引,因为np.where(array>4)[0]它看起来像......"丑陋".


附录

我理解(从一些答案)它实际上只是一个元素的元组.我仍然不明白为什么要以这种方式提供输出.为了说明这是不理想的,请考虑以下错误(这首先激发了我的问题):

>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9])
>>> pippo = np.where(array>4)
>>> pippo + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
Run Code Online (Sandbox Code Playgroud)

所以你需要做一些索引来访问实际的索引数组:

>>> …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy

32
推荐指数
2
解决办法
3万
查看次数

Python 2.7:仅从其句柄(而不是其路径)获取文件的大小

我正在编写一个需要根据文件大小(以字节为单位)对文件执行操作的函数。我想尽量减少传递给函数的参数数量,所以我只会将句柄传递给已经打开的文件,并让函数获取大小。有没有一种优雅的方法来做到这一点?

我正在尝试以下操作,os.path.getsize(os.path.abspath(file_id))但它不起作用:

def datafile_profiler(file_id):
    filesize = os.path.getsize(os.path.abspath(file_id))

    #[...] continue doing things with the file, based on the size in bites

    return stuff
Run Code Online (Sandbox Code Playgroud)

然后,从“主代码”

file_id = open(filepath, "rb")
stuff = datafile_profiler(file_id)
file_id.close()
Run Code Online (Sandbox Code Playgroud)

欢迎任何建议(也是一种完全不同的方法)。谢谢。

python file filesize python-2.7

2
推荐指数
1
解决办法
937
查看次数

标签 统计

python ×2

arrays ×1

file ×1

filesize ×1

numpy ×1

python-2.7 ×1