小编JCO*_*idl的帖子

使用 NumPy 的 sum 时避免循环

我经常需要对较大的 NumPy 数组的某些行或列进行求和。例如,拿这个数组:

>>> c = np.arange(18).reshape(3, 6)
>>> print(c)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]]
Run Code Online (Sandbox Code Playgroud)

假设我只想在行索引为 0 或 2 的地方求和,并且列索引为 0、2、4 或 5。换句话说,我想要子数组的总和

[[ 0  2  4  5]
 [12 14 16 17]]
Run Code Online (Sandbox Code Playgroud)

我通常使用 NumPy 非常有用的ix_方法来做到这一点;例如

>>> np.sum(c[np.ix_([0,2],[0,2,4,5])])
70
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。但是,现在假设我有一个不同的数组,e, ,c, ,但有两个前导维度。所以它的形状是 (2,3,3,6) 而不是 (3,6):

e = np.arange(108).reshape(2, 3, 3, 6)
Run Code Online (Sandbox Code Playgroud)

(请注意,我使用的实际数组可能包含任何随机整数;它们不包含像本例那样的连续整数。)

我要做的是对每个行/列组合进行上面的计算。以下适用于这个简单的示例,但对于具有更多维度的较大数组,这可能非常非常慢:

new_sum = np.empty((2,3))
for i …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy

5
推荐指数
1
解决办法
81
查看次数

通过bash脚本将参数传递到/ bin / bash

我正在编写一个bash脚本,该脚本需要多个命令行参数(可能包括空格),并将所有参数通过登录shell传递给程序(/ bin / some_program)。从bash脚本调用的登录shell将取决于用户的登录shell。假设在此示例中,用户使用/ bin / bash作为其登录shell ...但是它可能是/ bin / tcsh或其他任何东西。

如果我知道将有多少个参数传递给some_program,则可以在bash脚本中添加以下行:

#!/bin/bash
# ... (some lines where we determine that the user's login shell is bash) ...
/bin/bash --login -c "/bin/some_program \"$1\" \"$2\""
Run Code Online (Sandbox Code Playgroud)

然后按以下方式调用上述脚本:

my_script "this is too" cool
Run Code Online (Sandbox Code Playgroud)

通过上面的示例,我可以确认some_program接收到两个参数“ this too too”和“ cool”。

我的问题是...如果我不知道会传递多少个参数怎么办?我想将所有发送到my_script的参数传递给some_program。问题是我不知道该怎么做。以下是一些无效的内容

/bin/bash --login -c "/bin/some_program $@"     # --> 3 arguments: "this","is","too"
/bin/bash --login -c /bin/some_program "$@"     # --> passes no arguments
Run Code Online (Sandbox Code Playgroud)

bash

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

将文本和文件内容发送到标准输入,而不使用临时文件

我们知道将文本文件 的内容发送file.txt到从标准输入读取的脚本很简单:

the_script < file.txt
Run Code Online (Sandbox Code Playgroud)

假设我想做与上面相同的事情,除了我想发送到脚本的额外文本行,然后是文件的内容?当然一定有比这更好的方法:

echo "Here is an extra line of text" > temp1
cat temp1 file.txt > temp2
the_script < temp2
Run Code Online (Sandbox Code Playgroud)

这可以在不创建任何临时文件的情况下完成吗?

unix linux scripting

4
推荐指数
1
解决办法
4314
查看次数

标签 统计

arrays ×1

bash ×1

linux ×1

numpy ×1

python ×1

scripting ×1

unix ×1