2017-10-05 50 views
0

一个例子名单信:改变字符串中

eword_list = ["a", "is", "bus", "on", "the"] 
alter_the_list("A bus station is where a bus stops A train station is where a train stops On my desk I have a work station", word_list) 
print("1.", word_list) 

word_list = ["a", 'up', "you", "it", "on", "the", 'is'] 
alter_the_list("It is up to YOU", word_list) 
print("2.", word_list) 

word_list = ["easy", "come", "go"] 
alter_the_list("Easy come easy go go go", word_list) 
print("3.", word_list) 

word_list = ["a", "is", "i", "on"] 
alter_the_list("", word_list) 
print("4.", word_list) 

word_list = ["a", "is", "i", "on", "the"] 
alter_the_list("May your coffee be strong and your Monday be short", word_list) 
print("5.", word_list) 

def alter_the_list(text, word_list): 
    return[text for text in word_list if text in word_list] 

我试图从单词的列表,它是文本串在一个单独的字删除任何字。在检查单词列表中的元素都是小写字母之前,应该将文本字符串转换为小写字母。字符串中没有标点符号,单词参数列表中的每个单词都是唯一的。我不知道如何解决它。

输出:

1. ['a', 'is', 'bus', 'on', 'the'] 
2. ['a', 'up', 'you', 'it', 'on', 'the', 'is'] 
3. ['easy', 'come', 'go'] 
4. ['a', 'is', 'i', 'on'] 
5. ['a', 'is', 'i', 'on', 'the'] 

预期:

1. ['the'] 
2. ['a', 'on', 'the'] 
3. [] 
4. ['a', 'is', 'i', 'on'] 
5. ['a', 'is', 'i', 'on', 'the'] 
+0

'list(set(word_list)--set(setence.lower().split() )'。 –

回答

1

我已经做了这样的:

def alter_the_list(text, word_list): 
    for word in text.lower().split(): 
     if word in word_list: 
      word_list.remove(word) 

text.lower().split()返回text所有空格分隔的标记列表。

关键是你需要改变word_list。仅返回新的list是不够的;您必须使用Python 3's list methods就地修改列表。

0

你的主要问题是你从你的函数返回一个值,但是忽略它。你必须将其保存以某种方式打印出来,如:

word_list = ["easy", "come", "go"] 
word_out = alter_the_list("Easy come easy go go go", word_list) 
print("3.", word_out) 

你印什么是原来的单词列表,而不是函数结果。

你忽略文本参数的功能。在列表理解中重用变量名称作为循环索引。得到了不同的变量名,如

return[word for word in word_list if word in word_list] 

您还必须涉及您生成列表的逻辑文本。请记住,您在给定的文本中查找而不是的文字。

最重要的是,学习基本的调试。 看到这个可爱的debug博客寻求帮助。

如果没有其他问题,请学会使用简单的print语句来显示变量的值并跟踪程序执行。

这是否让你朝着解决方案迈进?

1

如果结果列表的顺序不要紧,你可以使用集:

def alter_the_list(text, word_list): 
    word_list[:] = set(word_list).difference(text.lower().split()) 

此功能将更新到位word_list由于分配到列表中片与word_list[:] = ...

+0

这应该是我见过的最快的编辑和downvote。 – mhawke

+0

那么,我只负责这些行为的一个** :-)我其实认为这是一个有用的答案。 +1 –

+0

@ChristianDean:感谢编辑然后:) – mhawke

0

我喜欢@Simon的答案更好,但如果你想在两个列表解析中做:

def alter_the_list(text, word_list): 
    # Pull out all words found in the word list 
    c = [w for w in word_list for t in text.split() if t == w] 
    # Find the difference of the two lists 
    return [w for w in word_list if w not in c] 
+0

这实际上可以在一个列表中理解:'[word_list中的单词如果单词不在setence.lower()。split()]中,它仍然是相当可读。 –