有没有一种方法可以在python中编写“ for”循环和“ If Else”,从而搜索一个句子并找到以相同字母开头和结尾的单词数量? 我试过写类似的东西:
sentence = "Mom knock the door"
list = sentence.split()
for word in sentence:
if ...
答案 0 :(得分:1)
只需将字符串开头的字符与字符串结尾的字符进行比较,如下所示:
if word[0] == word[-1]:
如果不区分大小写,请首先通过调用以下单词来降低该单词:
word = word.lower()
答案 1 :(得分:1)
words_list = sentence.split()
new_words_list = []
for word in words_list:
if word[0] == word[-1]:
new_words_list.append(word)
print('Number of words that starts and ends with same letter - {}'.format(len(new_words_list)))
您也可以通过列表理解来做到这一点:
new_words_list = [word for word in words_list if word[0] == word[-1]]
如果不想区分大小写,请使用word[0].lower()
和word[-1].lower()
而不是word[0]
和word[-1]
答案 2 :(得分:1)
上面的答案都很聪明,我更喜欢以函数式编程的方式来处理它,就像这样:
sentence = "Mom knock the door"
def is_same_letter_at_begin_end(word):
return word and word[0].lower() == word[-1].lower()
target_words = list(filter(is_same_letter_at_begin_end, sentence.split()))
print(target_words)
print(len(target_words))
答案 3 :(得分:0)
list = sentence.split(" ")
count = 0
for word in list:
lc_word = word.lower()
if lc_word[0] == lc_word[-1]:
count +=1
答案 4 :(得分:0)
lst = sentence.split()
num_words = 0
for i in lst:
low = i.lower()
if low[0] == low[len(low)-1]:
num_words += 1
return num_words
答案 5 :(得分:0)
list
或set
理解不区分大小写:
sentence = "Mom knock the door, mom"
all_words_count = len([ word for word in sentence.split() if word[0].lower() == word[-1].lower() ])
uniq_words_count = len({word.lower() for word in sentence.split() if word[0].lower() == word[-1].lower()})
print(all_words_count) #=> 3
print(uniq_words_count) #=> 2