简体   繁体   English

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

[英]Count how many words have the same beginning and ending letter/Python

QUESTION : The variable sentence stores a string. 问题 :可变句子存储一个字符串。 Write code to determine how many words in sentence start and end with the same letter, including one-letter words. 编写代码以确定句子中有多少个单词以同一字母开头和结尾,包括一个字母的单词。 Store the result in the variable same_letter_count. 将结果存储在变量same_letter_count中。

I've tweaked this a few different ways but I still can't figure it out. 我已经用几种不同的方式进行了调整,但是我仍然无法弄清楚。 Any help + explanation is appreciated so I know how to handle this the next time. 任何帮助+说明表示赞赏,所以我知道下次如何处理。

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)

I'm getting an answer of 1, the correct answer is 2. 我得到的答案是1,正确的答案是2。

You can take advantage of the fact the Python's booleans can be treated like zeros and ones and just add up all the boolean values of the test word[0] == word[-1] . 您可以利用以下事实:可以将Python的布尔值视为零和一,然后将测试word[0] == word[-1]所有布尔值相加即可。 The expression: 表达方式:

[w[0] == w[-1] for w in sentence.split()] 

evaluates to a list like [True, False, False...] . 计算结果为[True, False, False...]类的列表。 Taking the sum of that is the same as counting the number of True values and is a very typical way of doing something like this in Python. 将其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
if d[0] == d:
    same_letter_count = same_letter_count + 1
elif d[-1] == d:
    same_letter_count = same_letter_count + 1

This checks if the first letter is equal to the entire word, or if the last letter is equal to the entire word. 这将检查第一个字母是否等于整个单词,或者最后一个字母是否等于整个单词。 Therefore you are only counting "a". 因此,您仅在计算“ a”。 Instead try 试一试

if d[0] == d[-1]:
    same_letter_count = same_letter_count + 1

A quick solution by pandas : pandas提供的快速解决方案:

s = pd.Series(sentence.split(' '))
(s.str[0] == s.str[-1]).sum()

gives answer 2 . 给出答案2

You can even get those words: 您甚至可以得到这些话:

s[s.str[0] == s.str[-1]]

gives: 给出:

0    students
6           a
dtype: object
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM