Skip to main content
 首页 » 编程设计

Python之处理字符串中的特定字符

2025年05月04日15TianFang

def value(x): 
 
s = "Since 2012, Champion Data has boxed players in five categories, ranging from 'elite' to 'poor', based on a complicated formula assessing their most recent form. Players who have yet to debut, played only sparingly or are returning from long-term injuries (less than 10 games in two seasons) are placed in a sixth category named, appropriately, '?'. " 

目的是求和参数x在文本中不同出现次数的索引,除以出现次数,再除以文本长度。 我尝试了无数次,但似乎无法弄清楚。

请您参考如下方法:

您可以使用枚举来获取索引,例如:

indices = [i for i, j in enumerate(s) if x == j]

您可以找到索引的总和作为 sum(indices),出现的次数作为 len(indices) 和字符串的长度作为 len(s )

然后您的最终结果可以计算为

返回总和(指数)/(len(指数)*len(s))