python - 使 tqdm 等函数在 Python 中接受不同类型的参数

标签 python parameter-passing tqdm

这不是 tqdm 特有的问题,而是一个有关在 Python 中将参数传递给函数的通用问题。我想实现以下功能,而不必在 tqdm 下复制整个 block 。任何帮助将不胜感激。

if flag == True:
    with tqdm(dataloader, total=args.num_train_batches) as pbar:
else:
    with tqdm(dataloader) as pbar:

更具体地说,我可以通过这样的方式传递参数吗?

if flag == True:
    tqdm_args = dataloader, total=args.num_train_batches
else:
    tqdm_args = dataloader
with tqdm(tqdm_args) as pbar:

最佳答案

这实际上很简单,因为他们在制作Python时似乎就想到了这一点。您可以使用Python的ternary operator为此,请将上面的内容压缩为一行:

with tqdm(dataloader, total=args.num_train_batches if flag else None) as pbar:
  # ...

编辑:用您提到的首选方法回答,是的。这也是有可能的。如果将这些参数放入列表(或字典,如果有关键字参数),然后在列表的前面放入 * (或 ** 对于字典) name 当调用该函数时,它将列表解压缩为一组参数。

使用列表的示例:

if flag: # if flag is a boolean, putting "== True" does nothing
    tqdm_args = [dataloader, None, args.num_train_batches]
else:
    tqdm_args = [dataloader]
with tqdm(*tqdm_args) as pbar:
    # ...

字典示例:

if flag:
  tqdm_kwargs = {"iterable": dataloader, "total": args.num_train_batches}
else:
  tqdm_kwargs = {"iterable": dataloader}
with tqdm(**tqdm_kwargs) as pbar:
  # ...

很高兴为您提供帮助!

关于python - 使 tqdm 等函数在 Python 中接受不同类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64071843/

相关文章:

python - 如何创建不同点大小的图形?

python - 为什么 `imshow` 以彩色显示 2D(非 RGB)数组,如何将这样的彩色图像导出到 .png 文件?

python - pandas DataFrame DatetimeIndex 切片错误

url - 数据表 - 如何在 url 中传递搜索参数

python - 如何处理 python 参数中的引号

python - 将 tqdm 与延迟执行与 python 中的 dask 相结合

python - 如何在多处理中结合 TimeoutError 和 tq​​dm 进度条?

python - 如何比较Python和selenium中的字符串

javascript - 有没有办法记住从参数传递的函数 - (useCallback) exhaustive-deps

python - Python tqdm 的输出说明。