gpt4 book ai didi

Python累积条件逻辑

转载 作者:行者123 更新时间:2023-11-28 21:27:39 25 4
gpt4 key购买 nike

我正在努力解决以下问题的逻辑,我知道即使我确定了逻辑,我也可能会笨拙地实现它,所以任何建议都会很棒。

我有一个代表文件的字典:

the_file = {'Filename':'x:\\myfile.doc','Modified':datetime(2012,2,3),'Size':32412}

我有一个过滤器列表,我想过滤文件字典以确定匹配项。

filters = [
{'Key':'Filename','Criteria':'Contains','Value':'my'},
{'Key':'Filename','Criteria':'Does not end with','Value':'-M.txt'},
{'Key':'Modified','Criteria':'After','Value':datetime(2012,1,1)}
]

我最好尝试创建一个函数来执行此操作(但行不通):

def is_asset(the_file, filters):
match = False
for f in filters:
if f['Key'] == u'Filename':
if f['Criteria'] == u'Contains':
if f['Value'] in the_file['Filename']:
match = True
elif f['Criteria'] == u'Starts with':
if the_file['Filename'].startswith(f['Value']):
match = True
elif f['Criteria'] == u'Ends with':
if the_file['Filename'].endswith(f['Value']):
match = True
elif not f['Criteria'] == u'Does not end with':
if the_file['Filename'].endswith(f['Value']):
match = False
elif f['Criteria'] == u'Equals':
if os.path.basename(the_file['Filename']) == f['Value']:
match = True
elif f['Criteria'] == u'Does not contain':
if f['Value'] in the_file['Filename']:
match = False
elif f['Key'] == u'Modified':
mtime = int(os.path.getmtime(the_file['Filename']))
if f['Criteria'] == u'Before':
if f['Value'] > datetime.fromtimestamp(mtime):
the_file['Modified'] = mtime
match = True
elif f['Criteria'] == u'After':
if f['Value'] < datetime.fromtimestamp(mtime):
the_file['Modified'] = mtime
match = True
elif f['Key'] == u'Size':
size = long(os.path.getsize(the_file['Filename']))
if f['Criteria'] == u'Bigger':
if f['Value'] < size:
the_file['Size'] = size
match = True
elif f['Value'] > size:
the_file['Size'] = size
match = True
if match:
return the_file

最佳答案

与其尝试在一个宏功能中完成,不如将其分解成更小的步骤。

filenamecondmap = {
u'Contains': operator.contains,
u'Does not end with': lambda x, y: not x.endswith(y),
...
}

...

condmap = {
u'Filename': filenamecondmap,
u'Modified': modifiedcondmap,
...
}

然后遍历结构直到你有条件,然后执行它。

condmap[u'Filename'][u'Contains'](thefile['Filename'], 'my')

关于Python累积条件逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10407633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com