bad_stubs = [ 'test', 'blabla' ]
input = [ 'S01_test', 'S02_ahah', 'S03_blabla' ]
#Gets an item from a list, if not there gives None
def lget(list, index, default=None):
return list[index] if len(list) > index else default
results = [i for i in input if lget(i.split('_'), 1) not in bad_stubs]
使用列表理解
发电机也可用于:
^{pr2}$注意:
i.split('_')[1]
样式将错误,如果没有存根(项目在您可以使用列表理解来完成此操作:
或使用^{} :
^{pr2}$如果您在
python-3.x
上,请记住用list()
包装{a2},因为它返回一个迭代器:我可能更喜欢使用
filter()
和lambda
,而不是列表压缩,但是从一个非常基本的时间安排来看,理解似乎更快。在相关问题 更多 >
编程相关推荐