计算多少个单词具有相同的开始和结束字母/ Python

Dwr*_*244 0 python

问题:可变句子存储一个字符串。编写代码以确定句子中有多少个单词以同一字母开头和结尾,包括一个字母的单词。将结果存储在变量same_letter_count中。

我已经用几种不同的方式进行了调整,但是我仍然无法弄清楚。任何帮助+说明表示赞赏,所以我知道下次如何处理。

sentence = "students flock to the arb for a variety of outdoor activities 
such as jogging and picnicking"

same_letter_count = 0
sentence_split = sentence.split(' ')
sent_length = len(sentence_split)
#print(sent_length)
# Write your code here.
for d in sentence_split:
    #print(d[0])
    if d[0] == d:
        same_letter_count = same_letter_count + 1
    elif d[-1] == d:
        same_letter_count = same_letter_count + 1
print(same_letter_count)
Run Code Online (Sandbox Code Playgroud)

我得到的答案是1,正确的答案是2。

Mar*_*yer 5

您可以利用以下事实:可以将Python的布尔值视为零和一,然后将测试的所有布尔值相加即可word[0] == word[-1]。表达方式:

[w[0] == w[-1] for w in sentence.split()] 
Run Code Online (Sandbox Code Playgroud)

评估为的清单[True, False, False...]。取其sum与计True数值的数量相同,是在Python中执行此类操作的一种非常典型的方法。

sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = sum(w[0] == w[-1] for w in sentence.split())
# 2
Run Code Online (Sandbox Code Playgroud)