我有如下两个列表
f = ['sum_','count_','per_']
d = ['fav_genre','sum_fav_event','count_fav_type','per_fav_movie']
所以我想将 f 中每个字符串的 lstrip 应用于列表 d 的所有项目,这样我就可以得到
d = ['fav_genre','fav_event','fav_type','fav_movie']
我想使用列表理解来做到这一点。 但我知道我也可以用其他方式做到这一点,比如使用 re.sub,每次对 d 的列表项应用替换
#example
d = [re.sub(r'.*fav', 'fav', x) for x in d] #####gives what i want
## but if fav (which in this case a matching pattern) is not there in d then this solution won't work
## d = ['fav_genre','sum_any_event','count_some_type','per_all_movie']
#re.sub can't be applied on this d(as before) as no matching char like 'fav' found
所以列表压缩是我选择做的..
到目前为止我已经试过了..
d_one = [x.lstrip('count_') for x in d] ###only count_ is stripped
# o/p- d-one = ['fav_genre', 'sum_fav_event', 'fav_type', 'per_fav_movie']
# so i c_n apply lstrip of each string from f on items of d
## why not apply all items lstrip in one go ### so tried
d_new = [x.lstrip(y) for y in f for x in d]
###['fav_genre', 'fav_event', 'count_fav_type', 'per_fav_movie', 'fav_genre', 'sum_fav_event', 'fav_type', 'per_fav_movie', 'fav_genre', 'sum_fav_event', 'count_fav_type', 'fav_movie']
所以它给了我应用的 lstrip 的每次迭代的结果
请建议我如何在列表理解中一次应用所有 lstrip(递归)。提前致谢。
最佳答案
试试这个:
>>> f = ['sum_','count_','per_']
>>> d = ['fav_genre','sum_fav_event','count_fav_type','per_fav_movie']
>>> [s[len(([p for p in f if s.startswith(p)]+[""])[0]):] for s in d]
['fav_genre', 'fav_event', 'fav_type', 'fav_movie']
我相信这会按预期处理所有情况。
关于python——在列表上应用 lstrip 的递归列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35263203/