我正在处理这个函数,我希望按照它们在原始列表中出现的顺序返回以指定标记结尾的L元素列表。
def has_last_token(s,word):
""" (list of str, str) -> list of str
Return a list of the elements of L that end with the specified token in the order they appear in the original list.
>>> has_last_token(['one,fat,black,cat', 'one,tiny,red,fish', 'two,thin,blue,fish'], 'fish')
['one,tiny,red,fish', 'two,thin,blue,fish']
"""
for ch in s:
ch = ch.replace(',' , ' ')
if word in ch:
return ch
所以我知道当我运行代码并测试我提供的示例时,它会检查
'one,fat,black,cat'
并看到该单词不在其中,然后继续检查下一个值
'one,tiny,red,fish'
在这里它识别单词fish并输出它。但代码不会检查最后一个有效的输入。如何检查所有值而不是检查直到它看到一个有效的输出?
预期产出
>>> has_last_token(['one,fat,black,cat', 'one,tiny,red,fish', 'two,thin,blue,fish'], 'fish')
>>> ['one,tiny,red,fish', 'two,thin,blue,fish']
答案 0 :(得分:0)
您将返回第一个匹配项并退出该功能。您希望从循环中生成(创建生成器)或构建列表并返回该列表。我只想在列表理解中使用endswith
。我还要重新命名,以明确是什么。
def has_last_token(words_list, token):
return [words for words in words_list if words.endswith(token)]
答案 1 :(得分:0)
如果你能更好地理解答案,我会尽量回答你的问题,改变你的代码和你的逻辑。
如果您return ch
,您将立即终止该功能。
实现目标的一种方法是在循环之前简单地声明list
,然后相应地将所需的项追加到该列表中。返回值将是该列表,如下所示:
def has_last_token(s, word):
result = []
for ch in s:
if ch.endswith(word): # this will check only the string's tail
result.append(ch)
return result
PS:根据函数的docstring
,ch.replace()
是不必要的
答案 2 :(得分:0)
另一种方法是使用rsplit
将最后一个标记从字符串的其余部分拆分。如果你将第二个参数传递为1(可以在py3中使用命名参数maxsplit
但是py2不喜欢它),它会在一次拆分后停止,这就是我们所需要的。
然后,您可以使用filter
而不是显式循环来检查每个字符串是否有word
作为其最终标记,并返回仅包含word
作为其最终字符串的字符串的列表令牌。
def has_last_token(L, word):
return filter(lambda s: s.rsplit(',', 1)[-1] == word, L)
result = has_last_token(['one,fat,black,cat',
'one,tiny,red,fish',
'two,thin,blue,fish',
'two,thin,bluefish',
'nocommas'], 'fish')
for res in result:
print(res)
输出:
一个,微小的,红,鱼
2,薄,蓝色,鱼