首页 > 解决方案 > 如何使 tqdm 的总和等于两个 zip 变量的值的长度?

问题描述

现在,主 for 循环 tqdm 栏始终显示总数为 7。我的用户输入是一周中的所有 7 天,那就没问题了。问题是如果用户只输入 3 天或除 7 以外的任何其他值,它仍然显示总计 7。我该如何解决这个问题?


#!/usr/bin/env python3

import numpy as np
from tqdm import tqdm

print("""
+---------+----------------------+
| Days    | Mo Tu We Th Fr Sa Su |
| On  = 1 |  1  1  1  1  1  1  1 |
| Off = 0 |  0  0  0  0  0  0  0 |
+---------+----------------------+
""")

day_input = (int(val) for val in input("Enter days : ").split())
days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

print()

for val, day in tqdm(zip(day_input, days), position=2, colour='green', total=len(days)):
    if not val:
        continue
    first = np.busday_offset(np.datetime64('2022-01-01'), 0, roll='forward', weekmask=day)
    last = np.busday_offset(np.datetime64('1002022-01-01'), 1, roll='preceding', weekmask=day)
    delta = np.timedelta64(7, 'D')
    arange = np.arange(first, last, delta)
    array = np.array(arange)

    for a in tqdm(array, position=0, leave=False, desc=day, colour='blue'):
        pass

标签: pythonpython-3.x

解决方案


你必须改变:

day_input = (int(val) for val in input("Enter days : ").split())
days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

print()

for val, day in tqdm(zip(day_input, days), position=2, colour='green', total=len(days)):
    if not val:
        continue
    first = np.busday_offset(np.datetime64('2022-01-01'), 0, roll='forward', weekmask=day)
...

进入:

days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
input_days = [x[0] for x in filter(lambda d: d[1] != 0, zip(days, (int(val) for val in input("Enter days : ").split())))]

for day in tqdm(input_days, position=2, colour='green'):
    first = np.busday_offset(np.datetime64('2022-01-01'), 0, roll='forward', weekmask=day)
...

主要思想是根据用户的输入过滤天数,然后将仅包含选定天数的列表传递给tqdm.


推荐阅读