2017-04-10 36 views
0

我试图找出某个单词出现在哪个行号。例如说我有以下列表字典。这里每个列表都是段落中的一行。查找字典列表中的单词的所有发生

{1: ['They', 'seek', 'him', 'here'], 
2: ['they', 'seek', 'him', 'there'], 
3: ['those', 'Frenchies', 'seek', 'him', 'everywhere']} 

我想找到单词“他”出现的所有行。很明显,它只出现在第1,2,3行,但是如何让我的输出告诉我它出现在哪条线上?

回答

1

如果你只是想这样做一次,你可以用下面的:

[k for (k, v) in d.items() if 'him' in v] 

如果你打算做很多次,我会建议你建一个词典的单词映射到它出现的线英寸

0
z={1: ['They', 'seek', 'him', 'here'], 
2: ['they', 'seek', 'him', 'there'], 
3: ['those', 'Frenchies', 'seek', 'him', 'everywhere']} 

indices=[k for k in z if 'him' in z[k]] 
0

您可以遍历键并检查每个列表中是否存在搜索短语。请参阅此代码是否有帮助:

searchPhrase = "him" 
lines = [] 
for i in iDict: 
    if(searchPhrase in iDict[i]) 
     lines.append(i) 
print(lines) 
0

下面是简单的解决方案。

d={1: ['They', 'seek', 'him', 'here'], 2: ['they', 'seek', 'him', 'there'], 3: ['those', 'Frenchies', 'seek', 'him', 'everywhere']} 
word="him" 
lines=[] 
for i in d: 
    if word in d[i]: 
     lines.append(i) 
print lines 
相关问题