0
我有列表:比較列表和存儲索引值,如果列表匹配
- wordsindict
list2中
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,看看他們是否是容器d在list2內。如果是,我希望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的話,並存儲它們的索引值。這是不正確的,因爲list2中只有3個子列表。它爲每個索引值提供了自己的列表:
'population': [[], [2, 5], []
^ ^ ^
0 1 2
在這裏你可以看到,它的人口第一指標值之內出現,而是在第二子列表中的單詞索引值被記錄的只是'population': [1, 1]
代替。
簡而言之,我想要追加來自list2(0-2)的索引值,並且如果來自wordsindict的單詞在list2中出現多次,那麼再次從發現它的位置追加索引值。
wordsindict包含它們的鍵和list2應該搜索的發生。
如果您需要更多信息,請不要猶豫,問問!
dud,可以給其他SHORT例子嗎? ,我不明白...你想要索引值在一個字典與搜索的名字? – Milor123