我有两张清单:
清单2
wordsindict = ['somewhere', 'over', 'rainbow', 'bluebirds', 'fly', 'birds', 'fly', 'over', 'rainbow', 'why', 'why', 'double', 'time', 'population', 'long', 'takes', 'population', 'double', 'size', 'whoa', 'full', 'rainbow', 'way', 'double', 'rainbow', 'double', 'rainbow', 'way']
list2 = [['somewhere', 'over', 'rainbow', 'bluebirds', 'fly', 'birds', 'fly', 'over', 'rainbow', 'why', 'why'], ['double', 'time', 'population', 'long', 'takes', 'population', 'double', 'size'], ['whoa', 'full', 'rainbow', 'way', 'double', 'rainbow', 'double', 'rainbow', 'way']]
我正在提取wordsindict中的单词(删除重复项),并查看它们是否包含在列表2中。如果是,我希望取wordsindict中单词的索引值。下面是我目前拥有的代码:
listindex = {}
for word in wordsindict:
listindex[word] = []
for splittedLines_list in list2:
index_list = []
for i,j in enumerate(splittedLines_list):
if j == word:
index_list.append(i)
listindex[word].append(index_list)
此代码生成以下输出:
{'fly': [[4, 6], [], []], 'rainbow': [[2, 8], [], [2, 5, 7]], 'full': [[], [], [1]], 'bluebirds': [[3], [], []], 'takes': [[], [4], []], 'somewhere': [[0], [], []], 'double': [[], [0, 6], [4, 6]], 'over': [[1, 7], [], []], 'long': [[], [3], []], 'why': [[9, 10], [], []], 'whoa': [[], [], [0]], 'way': [[], [], [3, 8]], 'time': [[], [1], []], 'size': [[], [7], []], 'birds': [[5], [], []], 'population': [[], [2, 5], []]}
它从wordsindict中提取单词并存储它们的索引值。这是不正确的,因为列表2中只有3个子列表。它为每个索引值提供自己的列表:
例如'population': [[], [2, 5], []
^ ^ ^
0 1 2
在这里,您可以看到population确实出现在第一个索引值中,但是第二个子列表中的单词index value被记录,而不是简单地'population': [1, 1]
简单地说,我希望追加列表2(0-2)中的索引值,如果wordsindict中的单词在列表2中出现了不止一次,则从找到索引值的位置再次追加索引值
wordsindict包含它们的键,应该在列表2中搜索出现的项
如果您需要更多信息,请随时询问
如果我正确理解了这个问题,我想这就是你想要的:
输出:
如果希望列表索引包含该列表中的位置
相关问题 更多 >
编程相关推荐