是否可以像返回语句中那样使用 if/else 语句将方法 find_indexes 中的行数减少到只有 1 行?
def find_indexes(sentence, target):
indexes = [index for index, x in enumerate(sentence.split()) if target == x]
return indexes if indexes else False
target = 'dont'
sentence = 'we dont need no education we dont need no thought control no we dont'
print(find_indexes(sentence, target))
>> [1, 6, 13]
print(find_indexes(sentence, 'johndoe'))
>> False
我希望将方法更改为类似这样的方法,而无需编写两次理解:
def find_indexes(sentence, target):
return [index for index, x in enumerate(sentence.split()) if target == x] \
if [index for index, x in enumerate(sentence.split()) if target == x] else False
Write a procedure that takes a string of words separated by spaces (assume no punctuation or capitalization), together with a ”target” word, and shows the position of the target word in the string of words.
For example, if the string is:
we dont need no education we dont need no thought control no we dont
and the target is the word:
”dont”
then your procedure should return the list 1, 6, 13 because ”dont” appears at the 1st, 6th, and 13th position in the string. (We start counting positions of words in the string from 0.) Your procedure should return False if the target word doesn’t appear in the string
请您参考如下方法:
如果没有找到匹配项,则返回空列表。
def find_indexes(sentence, target):
return [index for index, x in enumerate(sentence.split()) if target == x]
indices = find_indexes("hi there bob", "bob")
if not indices:
print("No matches found")
else:
for i in indices:
print("Found match at {}".format(i))
