在另一个列表的任何值的列表中查找最高位置的单线

时间:2020-08-18 16:47:38

标签: python list

我必须执行以下操作。

给定一个文本,我必须找到所有数字之前的单词,直到一个属于check_words列表的停用词(种种stopwrods)为止

我的代码:

check_words = ['the', 'a', 'with','to']
mystring = 'the code to find the beautiful words 78 that i have to nicely check 45 with the snippet'
list_of_words = mystring.split()

在该特定文本中,我将在'78'和'45'之前进行检查,并且会一直返回到我发现任何单词check_words(但不超过8个单词)的地方。

执行此操作的代码可能是:

 preceding_chunks = []
for i,word in enumerate(list_of_words):
    if any(char.isdigit() for char in word):
       
        # 8 precedent words (taking into account that I can not slice with 8 back at the beginning)
        preceding_words = list_of_words[max(0,i-8):i]
        preceding_words[::-1]

        # I check from the end of the list towards the start
        for j,sub_word in enumerate(preceding_words[::-1]):
            if  sub_word in check_words:
                # printing out j for checking
                myposition = j
                print(j)
                real_preceding_chunk = preceding_words[len(preceding_words)-j:]
                print(real_preceding_chunk)
                preceding_chunks.append(real_preceding_chunk)
                break

此代码有效。 但是我有一种印象(也许我是错的),它可以通过使用一对衬板来实现,因此没有循环。 有想法吗?

注意: 这个问题是关于提高代码的可读性,试图摆脱循环以使代码更快,并试图使代码更好,这是zen zen的一部分。有时在堆栈溢出中不欢迎“使事情变得更好”,请不要降级,因为那样。

注意2:我以前做过的一些检查:

Finding the position of an item in another list from a number in a different list

Finding the index of an item in a list

Python: Find in list

0 个答案:

没有答案