给定一个字符串列表,返回字符串长度为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
你最好的办法是使用列表理解。列表包含三个部分:
例如,我们可以说
这将产生名单
我们可以添加第三行(过滤),只得到奇数:
在您的特殊情况下,我们不关心转换部分。我们只想输出符合您标准的单词:
这会给你一张单子。现在你只需要得到列表的长度:
想把它变成函数吗?给你:
这里有一些问题:
当你在每个单词上循环时,你在循环中
return
count
,而不是在循环结束时在结尾。这就是为什么你总是得到1
。你总是
count += 1
,即使x
是False
。x
取列表的第一个和最后一个项目,而不是列表中每个单词的第一个和最后一个字母。最后,将
bool
x
隐藏在for
循环中。提示
为什么不把它分成两个功能呢?你知道吗
第一个函数
match_end(word)
返回bool
或True
或False
。你知道吗首先,它通过切片将变量
first
和last
设置为字符串的第一个和最后一个字母。接下来,如果第一个字母和最后一个字母相同,并且单词的长度小于三个,那么它就是
return
sTrue
。否则,它是return
的False
。这是用Python的Ternary Operator完成的。第二个函数
match_ends(words)
包含一个字符串列表(与原来的一样),它迭代list
中的每个单词。你知道吗对于列表中的每个单词,它将测试
match_end(word)
是否返回True
。你知道吗如果是这样,则将计数增加
1
。否则,它什么也不做(增量按
0
计数)。最后,它返回
count
。相关问题 更多 >
编程相关推荐