python——在列表上应用 lstrip 的递归列表理解

标签 python regex list recursion list-comprehension

我有如下两个列表

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/

相关文章:

python - df.duplicated() 误报?

javascript - 获取索引处字符的 ANSI 颜色

python - 列表列表更改意外地反射(reflect)在子列表中

android - 如何将 List<ParseUser> 应用于 MultiAutoCompleteTextView?

python - 在单核上运行的 python 3.x/Windows 7 上的多进程 map-reduce

python - 如何 "send keys"到 Canvas 元素的持续时间更长?

python - 将数字转换为二进制字符串

c# - 如何检查 Regex 表达式是否与 C# 中的整个字符串匹配?

java - 我的字符串的准确正则表达式是什么?

java - 为什么 List<SubClass> 与 List<T extends SuperClass> 不兼容?