【发布时间】:2016-05-17 17:39:03
【问题描述】:
我有两个列表如下
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(递归)。提前致谢。
【问题讨论】:
-
我不认为你真的想在这里使用
lstrip。lstrip不会像您想要的那样删除字符串前缀,而是从参数中删除由任何字符组成的前缀。因此,如果您尝试从"notable"中删除'count_',您将得到"able"。我不认为你想要那个。 -
你能解释一下为什么它必须是递归的吗?这是一些扭曲的任务吗?如果它必须是递归的,那么你可以期望的最好的就是一个只有一行的函数。
-
@timgeb-yes,这里是递归,我的意思是,当我得到 lstrip 的每个迭代结果应用(结果)时,为什么不在第一个 lstrip 结果上应用第二个 lstrip,直到 f 的最后一项...因此递归调用列表 f 以获取项目并将该项目的 lstrip 应用于列表 d 每次。
-
@TomKarzes-你能解释一下我是否在 'count_notable_authors' 上应用 lstrip('count_') .. 为什么之前不能也被替换。但在其他情况下,'count_xyz_author' 它只会删除count_'并保持'xyz-author'..刚开始研究python,所以没有深入的概念想法..请回答为什么会这样??
-
因为
lstrip不会做你认为的事情。如果你给它一个前缀'count_',它只是一组字符,和'ntc_uo'没有区别。它是无序的。它将继续从字符串的前面删除任何这些字符,直到遇到不在集合中的字符。
标签: python regex list recursion list-comprehension