小编qou*_*ify的帖子

为什么 ${*// /*} 不能在命令行参数中用 * 替换空格?

我希望我的脚本执行其所有整数参数的乘积。我没有执行循环,而是尝试用替换空白*,然后计算操作。但我得到了以下我不明白的结果:

#!/bin/bash
# product.sh

echo $(( ${*// /*} ))  # syntax error with ./product.sh 2 3 4
args=$*
echo $(( ${args// /*} ))  # ./product.sh 2 3 4 => outputs 24
Run Code Online (Sandbox Code Playgroud)

当使用中间变量工作正常时,第一个会产生错误,这是怎么回事?

bash replace

8
推荐指数
4
解决办法
452
查看次数

键入一个带有可调用的函数

我有很多具有相同签名的函数,比如(int, int) -> int.

有没有办法用 a Callable(或其他东西)来输入这些函数,以避免为每个函数指定参数类型和返回类型?我想做类似的事情(但显然失败了):

from typing import Callable

f: Callable[[int, int], int]
def f(x, y):  #  with the previous line, this is equivalent to 'def f(x: int, y: int) -> int:'
    ...
Run Code Online (Sandbox Code Playgroud)

运行 mypy 结果:

file.py:4: error: Name "f" already defined on line 3
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

python type-hinting mypy python-typing

6
推荐指数
1
解决办法
108
查看次数

使用设置文字更快地设置包含

下面我会10_000_000检查 if 是否10在 中{0, ..., 9}

在第一个检查中,我使用中间变量,在第二个检查中,我使用文字。

import timeit

x = 10
s = set(range(x))
number = 10 ** 7

stmt = f'my_set = {s} ; {x} in my_set'
print(f'eval "{stmt}"')
print(timeit.timeit(stmt=stmt, number=number))

stmt = f'{x} in {s}'
print(f'eval "{stmt}"')
print(timeit.timeit(stmt=stmt, number=number))
Run Code Online (Sandbox Code Playgroud)

输出:

eval "my_set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} ; 10 in my_set"
1.2576093
eval "10 in {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}" …
Run Code Online (Sandbox Code Playgroud)

python performance

3
推荐指数
1
解决办法
132
查看次数

使用 $(...) 获取子命令的错误代码

在这段代码中:

echo hello > hello.txt
read X <<< $(grep hello hello.txt)
echo $?
Run Code Online (Sandbox Code Playgroud)

$?指的是读取语句的退出代码,它是 0。有没有办法知道grep失败(例如,如果hello.txt已被另一个进程删除)而不将read和拆分为grep两个语句(即,先grep检查$?然后检查read)。

bash exit-code

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

html文件中格式良好的python代码

在 HTML 页面中显示 python 代码的选项有哪些?

我不想在页面中执行 python 代码,但只生成 HTML/CSS 页面,显示格式很好(例如,语法突出显示)python 代码片段,例如,通过 stackoverflow。

基本上我想要一个将 python 文件作为输入并生成 HTML/CSS 代码的工具。

html css

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