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 complete_word_list:
if i in dracula_list and i in complete_word_list:
dracula_list.append(complete_word_list[i:-1])
理想情况下,我会收到
['train', 'anhour']
解决方案
就个人而言,我认为使用单词的索引来查找比遍历列表更容易。
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 except
catch 来检查元素是否在列表中 ( 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)
推荐阅读
- php - 我可以在 laravel 8 中使用我的控制器来删除检入视图的行吗?
- ethereum - Web 应用程序无法与通过 Truffle 部署的以太坊智能合约正确通信
- version-control - 如何使用 DevOps 管理不同的“项目分支”
- laravel - 如何让 Google Auth 与 Laravel 一起使用?
- mysql-workbench - 无法通过加载数据本地 infile 查询在 MySQL Workbench 中导入 CSV 文件
- prestashop - 呈现模板期间引发异常(“未找到列类型“custom_text”的内容模板”)
- java - 单击按钮时我的应用程序崩溃(android studio)
- lambda - 扩展 ... lambda 的封闭父函数必须允许获取其地址
- dart - 构造函数中[和]的含义
- python - 分析输入和输出变量的python代码部分