Python还原二元曲线和三元曲线

2024-04-19 12:16:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个双曲线和三元组的列表:

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可以还原为其原始字符串。在

期望输出为:

^{pr2}$

Tags: 函数字符串列表stringnotbe结构do
2条回答

使用列表理解:

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

# Output: ['do not be sad']

试试这个

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

输出

^{pr2}$

我们可以把它做成一个很好的单管

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

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

相关问题 更多 >