问题:可变句子存储一个字符串。写代码到 确定句子中有多少个单词以相同的开头和结尾 字母,包括一个字母的单词。将结果存储在变量中 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)
我得到的答案是1,正确的答案是2。
答案 0 :(得分:5)
您可以利用Python的布尔值可以被视为零和一的事实,并且只需将测试word[0] == word[-1]
的所有布尔值相加即可。表达式:
[w[0] == w[-1] for w in sentence.split()]
评估为[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
答案 1 :(得分:1)
if d[0] == d:
same_letter_count = same_letter_count + 1
elif d[-1] == d:
same_letter_count = same_letter_count + 1
这将检查第一个字母是否等于整个单词,或者最后一个字母是否等于整个单词。因此,您仅在计算“ a”。而是尝试
if d[0] == d[-1]:
same_letter_count = same_letter_count + 1
答案 2 :(得分:0)
pandas
的快速解决方案:
s = pd.Series(sentence.split(' '))
(s.str[0] == s.str[-1]).sum()
给出答案2
。
您甚至可以得到这些单词:
s[s.str[0] == s.str[-1]]
给予:
0 students
6 a
dtype: object
答案 3 :(得分:0)
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(' ')
sentense_length = len(sentence_split)
for d in sentence_split:
if d[0] == d[-1]:
same_letter_count += 1
print(same_letter_count)