适用于任何布尔函数和可迭代的通用解决方案(有关仅查看 str.isalpha() 的版本,请参见下文):
def percentage(data, boolfunc):
"""Returns how many % of the 'data' returns 'True' for the given boolfunc."""
return (sum(1 for x in data if boolfunc(x)) / len(data))*100
text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"
print( percentage( text, str.isupper ))
print( percentage( text, str.islower ))
print( percentage( text, str.isdigit ))
print( percentage( text, lambda x: x == " " ))
输出:
62.5 # isupper
25.0 # islower
0.0 # isdigit
12.5 # lambda for spaces
schwobaseggl 的更好
return sum(map(boolfunc,data)) / len(data)*100
因为它不需要持久化列表,而是使用生成器。
编辑:仅使用 str.isalpha 字符并允许多个布尔函数的第二个版本:
def percentage2(data, *boolfuncs):
"""Returns how many % of the 'data' returns 'True' for all given boolfuncs.
Only uses str.isalpha() characters and ignores all others."""
count = sum(1 for c in data if c.isalpha())
return sum(1 for x in data if all(f(x) for f in boolfuncs)) / count * 100
text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"
print( percentage2( text, str.isupper, str.isalpha ))
print( percentage2( text, str.islower, str.isalpha ))
输出:
71.42857142857143
28.57142857142857