0

我有一个二元组和三元组的列表:

string = 'do not be sad'

a_list: = ['do', 'not', 'do not', 'be', 'not be', 'do not be', 'sad', 'be sad', 'not be sad']

我想知道是否有一个函数可以反转二元组和三元组a_list?我知道我可以加入所有字符串并删除重复项,但这会丢失句子的结构。我正在寻找是否有人有任何提示,以便a_list可以将其恢复为原始字符串。

期望的输出是:

b_list = ['do not be sad']
4

2 回答 2

1

尝试这个

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])

我还创建了几个测试用例来测试我的解决方案,它们都通过了

于 2016-02-18T12:26:12.023 回答
0

使用列表推导:

a_sentence = [" ".join(word for word in a_list if len(word.split()) == 1)]
print(a_sentence)

# Output: ['do not be sad']
于 2016-02-18T12:21:52.723 回答