给定一个字符串列表,返回字符串长度为3或更多的字符串数的计数,字符串的第一个和最后一个字符是相同的。
为了解决这个问题,我创建了以下函数,
def match_ends(words):
FirstL=words[0:1]
LastL=words[-1:]
x=len(words)>3 and FirstL == LastL
count=0
for x in words:
count+=1
return count
然后在这里测试,
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print ('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
# Calls the above functions with interesting inputs.
def main():
print ('match_ends')
test(match_ends(['abaa', 'xyzax', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 1)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
print
结果:
X got: 1 expected: 3
OK got: 1 expected: 1
OK got: 1 expected: 1
答案 0 :(得分:0)
这里有一些问题:
当你循环遍历每个单词时,你在循环中return
count
,而不是在循环结束时结束。这就是为什么你总是得到1
。
即使count += 1
为x
,您总是 False
。
x
占据列表的第一个和最后一个项目,而不是列表中每个单词的第一个和最后一个字母。
最后,您在bool
循环中隐藏x
for
。
<小时/> 的提示强>
为什么不把它分成两个函数?
def match_end(word):
first, last = word[0], word[-1:]
return True if first == last and len(word) >= 3 else False
def match_ends(words):
count = 0
for word in words:
count += 1 if match_end(word) else 0
return count
第一个函数match_end(word)
返回bool
或True
的{{1}}。
首先,它通过切片将变量False
和first
设置为字符串的第一个和最后一个字母。
接下来,last
s return
如果第一个字母与最后一个字母相同,并且单词的长度小于3。否则,True
s return
。这是通过Python的Ternary Operator。
第二个函数False
接受一个字符串列表(就像你的原始字符串一样)迭代match_ends(words)
中的每个单词。
对于列表中的每个字词,它会测试list
是否返回match_end(word)
。
如果是这样,它会将计数增加True
。
否则,它什么都不做(递增计数1
)。
最后,它返回0
。
答案 1 :(得分:-1)
这里最好的选择是使用列表理解。列表理解有三个部分:
例如,我们可以说
[ x * x # square the number
for x in range(5) ] # for each number in [0,1,2,3,4] `
将生成列表
[0 1 4 9 16]
我们可以添加第三条(过滤)行,只返回奇数:
[x * x
for x in range(5)
if x % 2] # divide x by 2, take the remainder -- if 1, output the number`
在您的特定情况下,我们不关心转换部分。我们只想输出符合您标准的单词:
[word
for word in word_list
if len(word) >= 3 and word[0] == word[-1] ]
这会给你一个清单。现在你只需要得到该列表的长度:
len( [word
for word in word_list
if len(word) >= 3 and word[0] == word[-1] ] )
想把它变成一个功能吗?你走了:
def count_matching_words(word_list):
return len([word
for word in word_list
if len(word) >= 3 and word[0] == word[-1]])