首页 > 解决方案 > 将列表的元素附加到迭代器的左侧或右侧到另一个列表

问题描述

我正在检查一个字符串并寻找特定单词的出现。如果迭代器与该单词匹配,我想将元素直接附加到它的左侧或右侧。

我试过使用枚举,但我只是继续在列表末尾附加元素。

complete_word_list = ['3', 'May', '.', 'Bistritz', '.', 'Left', 'Munich', 'at', '8:35', 'P.', 'M.', ',', 'on', '1st', 'May', ',', 'arriving', 'atVienna', 'early', 'next', 'morning', ';', 'should', 'have', 'arrived', 'at', '6:46', ',', 'but', 'train', 'dracula', 'anhour', 'late']

dracula_list = ['dracula','Dracula']
nearby_words = []

for i in complete_word_list:

    if i in dracula_list and i in complete_word_list:

        dracula_list.append(complete_word_list[i:-1])

理想情况下,我会收到

['train', 'anhour']

标签: python

解决方案


就个人而言,我认为使用单词的索引来查找比遍历列表更容易。

complete_word_list = ['3', 'May', '.', 'Bistritz', '.', 'Left', 'Munich', 'at', '8:35', 'P.', 'M.', ',', 'on', '1st', 'May', ',', 'arriving', 'atVienna', 'early', 'next', 'morning', ';', 'should', 'have', 'arrived', 'at', '6:46', ',', 'but', 'train', 'dracula', 'anhour', 'late']

dracula_list = ['dracula','Dracula']
nearby_words = []

for i in dracula_list:
    if i in complete_word_list: #if word was found in list
        found_word = complete_word_list.index(i) #returns index of word to find
        nearby_words.append(complete_word_list[found_word-1]) #index-1 is the element to the left
        if found_word+1 < len(complete_word_list): #include a check to keep indices in range of list
            nearby_words.append(complete_word_list[found_word+1]) #index+1 is element to the right
print(nearby_words)

编辑:按照建议,您可以使用try and exceptcatch 来检查元素是否在列表中 ( ValueError) 或者是否有任何相邻元素 ( IndexError):

complete_word_list = ['3', 'May', '.', 'Bistritz', '.', 'Left', 'Munich', 'at', '8:35', 'P.', 'M.', ',', 'on', '1st', 'May', ',', 'arriving', 'atVienna', 'early', 'next', 'morning', ';', 'should', 'have', 'arrived', 'at', '6:46', ',', 'but', 'train', 'dracula', 'anhour', 'late']
dracula_list = ['dracula','Dracula']
nearby_words = []

for i in dracula_list:
    try:
        found_word = complete_word_list.index(i)
        nearby_words.append(complete_word_list[found_word-1])
        nearby_words.append(complete_word_list[found_word+1])
    except (ValueError, IndexError):
        print('this is either not in the list of there was not an adjacent element on either side.')
print(nearby_words)

推荐阅读