我是python的新手,我只是想知道是否可以用一种更简单的方式而不使用for循环来重写它?代码下方给出了此函数的期望值示例。
def valid_words(dictionary, sentence:)
x =sentence.split()
y = dictionary.split()
newlist = []
`for i in x:`
`for j in y:`
`if i == j:`
`newlist.append(i)`
`return newlist`
例如,词典字符串“一个苹果香蕉香蕉梨草莓芒果”和句子字符串“你好芒果和香蕉百胜苹果!”会产生一个字符串列表[“ mango”,“ banana”]。
请注意,“苹果!”由于感叹号是该单词的一部分,因此未匹配为有效单词。
set
。一个集合就像一个列表,除了不能有相同值的倍数并且不跟踪顺序。注意,我选择not使用单词dictionary
作为变量名,因为在Python中有特殊含义。
def valid_words(valid, potential):
return list(set(valid.split()) & set(potential.split()))