これを試して
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])])
編集:ゾンドのコメントに応えて、回答を編集することにしました。さらに、この問題は非常に興味深いことがわかりました
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])
また、ソリューションをテストするためにいくつかのテストケースを作成しましたが、それらはすべて合格しました