查找字符串是否以列表的可变长度前缀之一开头 [英] Finding whether a string starts with one of a list's variable-length prefixes

查看:100
本文介绍了查找字符串是否以列表的可变长度前缀之一开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找出名称是否以列表的前缀开头,然后将其删除,例如:

I need to find out whether a name starts with any of a list's prefixes and then remove it, like:

if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]:
    name = name[2:]

以上内容仅适用于长度为2的列表前缀.对于可变长度前缀,我需要相同的功能.

The above only works for list prefixes with a length of two. I need the same functionality for variable-length prefixes.

它如何有效地完成(代码少,性能好)?

How is it done efficiently (little code and good performance)?

一个for循环在每个前缀上进行迭代,然后检查name.startswith(prefix)以根据前缀的长度最终对名称进行切片,但这是很多代码,可能效率低下,并且是非Pythonic的".

A for loop iterating over each prefix and then checking name.startswith(prefix) to finally slice the name according to the length of the prefix works, but it's a lot of code, probably inefficient, and "non-Pythonic".

有人有很好的解决方案吗?

Does anybody have a nice solution?

推荐答案

有点难以理解,但这可行:

A bit hard to read, but this works:

name=name[len(filter(name.startswith,prefixes+[''])[0]):]

这篇关于查找字符串是否以列表的可变长度前缀之一开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆