尝试这个
string = 'do not be sad'
string = string.split()
a_list = ['do', 'not', 'do not', 'be', 'not be', 'do not be', 'sad', 'be sad', 'not be sad']
new = []
for a in string:
for b in a_list:
if a == b:
new.append(b)
print([' '.join(new)])
输出
['do not be sad']
我们可以把它变成一个很好的单线
print([' '.join([b for a in string for b in a_list if a == b])])
编辑:针对 zondo 的评论,我决定编辑我的答案,而且我发现这个问题很有趣
a_list = ['do', 'not', 'do not', 'be', 'not be', 'do not be', 'sad', 'be sad', 'not be sad']
a_list = ['This', 'is', 'This is', 'my', 'is my', 'This is my', 'car', 'my car', 'is my car']
a_list = ['i', 'am', 'i am', 'a' , 'am a', 'i am a', 'boy', 'a boy', 'am a boy']
largest = max(a_list, key=len) # get the longest sub word in the list
# loop through and if all words of a sublist don't exist in the largest sub word then join them together
for elem in a_list:
sp = elem.split()
if all(i not in largest for i in sp):
if a_list.index(elem) < a_list.index(largest):
print([elem + ' ' + largest])
else:
print([largest + ' ' + elem])
我还创建了几个测试用例来测试我的解决方案,它们都通过了