尝试计算单词 true 中某些字母的数量,有什么更简单的方法可以做到这一点?
我希望有一个更简单的解决方案,可以给我 4 作为答案!
您可以使用集合,但确切的方法取决于确切的预期逻辑。
target = {'t', 'r', 'u', 'e'}
### counting each unique letter that is also in target
word = 'true'
len(set(word) & target)
# 4
word = 'test' # t and e are counted (once), not s
len(set(word) & target)
# 2
### counting all letters
# here t, e, t are counted, not s
sum(1 for c in word if c in target)
# 3