繁体   English   中英

从布尔列表中删除重复项

[英]removing duplicates from a bool list

我试图在列表中得到一个单词,然后在其中带有“。''的单词。 例如,如果这是一个列表

test_list = ["hello", "how", "are.", "you"]

它会选择“ you”一词,但我设法做到这一点,但我试图确保不会得到重复的词。 这是我到目前为止的

list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list 

您可以使用zip()list comprehension将整个代码简化为以下示例:

a = ['hello', 'how', 'are.', 'you']

def get_new_list(a):
    return [v for k,v in zip(a, a[1:]) if k.endswith('.')]

然后,要删除重复项(如有set() ,可以使用set() ,如下例所示:

final = set(get_new_list(a))

输出:

{'you'}

这不是基于您发布的代码,但是它应该完全按照您的要求进行。

def getWordAfterDot(words):
    for index, word in enumerate(words):
        if word.endswith('.') and len(words) - index > 1:
            yield words[index + 1]

多次调用此函数将产生带有句点的单词。

这是解决同一问题的另一种方法。

import itertools
from collections import deque

t = deque(map(lambda x: '.' in x, test_list)) # create a deque of bools
>>deque([False, False, True, False])

t.rotate(1) # shift it by one since we want the word after the '.'
>>deque([False, False, False, True])

set(itertools.compress(test_list, t)) # and then grab everywhere it is True
>>{'you'}

itertools配方是定义pairwise其为以一次迭代列表2有用:

def pairwise(iterable):
    a, b = it.tee(iterable)
    next(b, None)
    return a, b

您可以使用它创建以'.'结尾的单词之后的单词列表'.'

words = [n for m, n in zip(*pairwise(l)) if m[-1] == '.']

删除重复项:

seen = set()
results = [x for x in words if not (x in seen or seen.add(x))]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM