使用函数计算匹配值

时间:2017-03-18 12:08:57

标签: python

我有以下功能来检查dict值列表,以确定日期是否在今天之前(逾期)。我遇到的问题是每次调用函数时,overdue都被设置为零(因为函数再次被调用)。我需要使用全局变量吗?

from datetime import datetime

def overdue_tools(arg):
    overdue = 0
    today = datetime.now().date()
    try:
        due_date = datetime.strptime(arg, '%d/%m/%Y').date()
        if due_date < today:
            overdue += 1
    except (ValueError, TypeError):
        print('Cannot convert {} to a date.'.format(arg))
    result = '<b>|</b> {} tools are overdue'.format(overdue)
    return result

s = ['01/01/2016', '02/02/2017', '04/05/2017', '05/06/2017']

for i in s:
    print overdue_tools(i)

结果如下:

me@computer:~/code$ python test.py
<b>|</b> 1 tools are overdue
<b>|</b> 1 tools are overdue
<b>|</b> 0 tools are overdue
<b>|</b> 0 tools are overdue

我所追求的是:

<b>|</b> 2 tools are overdue

我不确定实现这一目标的最佳方法。谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

创建一个做一件事的谓词函数is_overdue(没有格式化/消息打印):

def is_overdue(arg):
    today = datetime.now().date()
    due_date = datetime.strptime(arg, '%d/%m/%Y').date()
    return due_date < today

然后过滤原始列表并计算剩余项目:

print "overdue tools count: %d" % len([t for t in s if is_overdue(t)])

您可以更改格式和异常处理以符合您的要求。

答案 1 :(得分:0)

您希望从函数中返回一个布尔值,并在每次True时计算:

from datetime import datetime

def is_overdue(arg):
    overdue = False
    today = datetime.now().date()
    try:
        due_date = datetime.strptime(arg, '%d/%m/%Y').date()
        if due_date < today:
            overdue = True
    except (ValueError, TypeError):
        print('Cannot convert {} to a date.'.format(arg))
    return overdue

s = ['01/01/2016', '02/02/2017', '04/05/2017', '05/06/2017']

number_overdue = 0
for i in s:
    if is_overdue(i):
        number_overdue += 1 

print '<b>|</b> {} tools are overdue'.format(number_overdue)

答案 2 :(得分:-1)

每次都可以将overdue变量传递给函数以保存其值:

In [43]: from datetime import datetime
    ...: 
    ...: def overdue_tools(arg, overdue):
    ...:     today = datetime.now().date()
    ...:     try:
    ...:         due_date = datetime.strptime(arg, '%d/%m/%Y').date()
    ...:         if due_date < today:
    ...:             overdue += 1
    ...:     except (ValueError, TypeError):
    ...:         print('Cannot convert {} to a date.'.format(arg))
    ...:     return overdue
    ...: 
    ...: s = ['01/01/2016', '02/02/2017', '04/05/2017', '05/06/2017']
    ...: overdue = 0
    ...: for i in s:
    ...:     overdue = overdue_tools(i, overdue)
    ...:     print('<b>|</b> {} tools are overdue'.format(overdue))
    ...:     
<b>|</b> 1 tools are overdue
<b>|</b> 2 tools are overdue
<b>|</b> 2 tools are overdue
<b>|</b> 2 tools are overdue