【发布时间】:2019-04-29 15:43:17
【问题描述】:
我有这个简单的功能:
keys = ['snmt1/metadata/table1/ref_table1_20190324124365.csv', 'snmt1/metadata/table2/table2_ref_20190324124365.csv', 'snmt1/metadata/table3/table3_20190324124365.csv']
def better_func(keys):
for item in keys:
split_key = item.split("/")
filename = str(split_key[-1])
prefixes = ['strm','ref','trunc']
if any(x in filename for x in prefixes):
location = filename.find(x)
if location == 0:
print True
else:
print "another false"
else:
print False
我需要的是“x”的值,这样我就可以使用 .find() 函数返回它的索引。上面的代码不起作用,因为它告诉我:
NameError:未定义全局名称“x”
我明白,但我如何才能像通常在 for 循环中那样访问“x”?
for x in my_list:
print x
【问题讨论】:
-
你想要
next()而不是any() -
你能再解释一下吗。添加 next() 将如何帮助我返回 x 的值? Any 在这里是正确的功能,它按预期工作,我只需要访问要在 .find() 中使用的 x 的值
-
x = next((x for x in prefixes if x in filename), None):和if x:(或者可能是filename.startswith(x)-- 假设您想要第一个,请对所有数学使用列表组合 -
@Chris_Rands 这个工作除了最后一次迭代,然后它抛出一个错误
Traceback (most recent call last): File "main.py", line 78, in <module> better_func(keys) File "main.py", line 26, in better_func if filename.startswith(x): TypeError: startswith first arg must be str, unicode, or tuple, not NoneType -
我可以将“None”的值更改为默认值,但这似乎不是很pythonic,以满足最后一次迭代。那问题对吗?