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))
关于Python - 处理字符串中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29413244/