def no_underscored_words(words_string):
'''Receives a string (word_string containing zero or
more comma separated words. Returns a list of words
in words_string that do not contain any underscore
character in them.'''
result = []
word_list = words_string.split(",")
for word in word_list:
if word != "_":
result.append(word)
return result
这就是我得到的,但失败了:(
任何建议都将不胜感激
问题要求
print(no_underscored_words('12,_init __,main'))并期望结果应为['12','main']
打印(no_underscored_words('my_list,your_list'))并期望结果应为[]
答案 0 :(得分:1)
替换
if word != "_":
与
if "_" not in word:
答案 1 :(得分:1)
让我们定义函数no_under
。为方便起见,我们在ipython
:
In [7]:: def no_under(word_string):
...: return [word for word in word_string.split(',') if not '_' in word]
...:
两个测试用例表明这可以按预期工作:
In [8]: no_under('12,_init__,main')
Out[8]: ['12', 'main']
In [9]: no_under('my_list,your_list')
Out[9]: []
该函数包含单个命令:
return [word for word in word_string.split(',') if not '_' in word]
word_string.split(',')
将逗号分隔的word_string
转换为单词列表。如果if
子句为True,则这些单词包含在最终列表中。 '_' in word
测试该单词是否包含下划线。如果它没有,它将包含在我们返回的最终列表中。
答案 2 :(得分:0)
def no_underscored_words(words_string):
'''Receives a string (word_string containing zero or
more comma separated words. Returns a list of words
in words_string that do not contain any underscore
character in them.'''
result = []
word_list = words_string.split(",")
for word in word_list:
if not('_' in word):
result.append(word)
return result
print(no_underscored_words('12,_init__,main'))
print(no_underscored_words('my_list,your_list'))
输出:
['12', 'main']
[]