问题:我有一个目录中的文件列表,我想检索与所有三个子字符串条件匹配的第一个文件。我基于此示例中的案例 1 解决方案,从查找匹配条件的第一个序列项中找到符合条件的第一个项
问题:但是,我发现如果我在生成器表达式中将 if-checks 的数量扩展到三个,那么我会得到一个 python: Python/compile.c:3437: stackdepth_walk: Assertion `depth >= 0' failed。中止(核心转储)
问题:这对我来说很特殊,因为我只测试了几个条件,它似乎不应该导致堆栈断言。有人可以解释为什么会这样吗?
下面的案例1重现了错误
案例 2 表明此方法仍然适用于两个 if 检查
案例 3 表明,如果我分解列表理解和下一次调用,此方法将起作用。
案例 4 是相同检查的替代解决方案,但作为正则表达式,并且有效。
#! /usr/bin/python
import re
files_in_dir = ['dp2_syouo_2013-05-16_0000.csv',
'dp1_torishima_2013-05-21_0000.csv',
'dp2_torishima_2013-05-22_0000.csv',
'dp1_hirokawa_2013-05-21_0000.csv',
'dp2_hirokawa_2013-05-22_0000.csv',
'dp2_syouo_2013-05-17_0000.csv',
'dp2_syouo_2013-05-18_0000.csv']
dp_string = "dp2"
date_string = "2013-05-22"
location_string = "torishima"
# case 1: Three filter checks, stackdepth_walk: Assertion
#python: Python/compile.c:3437: stackdepth_walk: Assertion `depth >= 0' failed.
# Abort (core dumped)
file_matched_1 = next( (file_in_dir for file_in_dir
in files_in_dir
if dp_string in file_in_dir
if location_string in file_in_dir
if date_string in file_in_dir), None)
print "case 1: " + file_matched_1;
# case 2: Two filter checks, works fine
file_matched_2 = next( (file_in_dir for file_in_dir
in files_in_dir
if dp_string in file_in_dir
if location_string in file_in_dir
), None)
print "case 2: " + file_matched_2
# case 3: Generate the list first with three filters, then get the first item
files_matched_3 = [file_in_dir for file_in_dir
in files_in_dir
if dp_string in file_in_dir
if location_string in file_in_dir
if date_string in file_in_dir]
file_matched_3 = next(iter(files_matched_3))
print "case 3: " + file_matched_3
# case 4: Put the three checks into a regex
date_location_regex = r'' + dp_string + '*.' + location_string + '*.' + date_string
file_matched_4 = next( (file_in_dir for file_in_dir
in files_in_dir
if re.search(date_location_regex, file_in_dir)), None)
print "case 4: " + file_matched_4