相对位置转绝对位置
假设我有一个包含单词的字符串列表,我该如何找到某个特定单词在整个列表中的绝对位置,而不是在字符串中的相对位置呢?
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
rel_0word2 = l[0].split().index('1word2') # equals 2
abs_0word2 = ??? # equals 5
提前谢谢你。
5 个回答
0
我想你是想说下面的内容:
def GetWordPosition(lst, word):
if not word in lst:
return -1
index = lst.index(word)
position = 0
for i in xrange(index):
position += len(lst[i])
return position
1
你只需要把你的生成器嵌套得当就行:
>>> sentences = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
>>> all_words = [w for words in sentences for w in words.split()]
>>> all_words
['0word0', '0word1', '0word2', '1word0', '1word1', '1word2', '2word0', '2word1']
>>> all_words.index('1word1')
4
或者,如果你想用迭代器来处理(比如说你在处理很多长字符串之类的),你可以试试使用 chain
函数(这是我最近的新宠)。
3
我不太明白你说的绝对定位是什么意思,下面是我的示例:
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
print [x for w in l for x in w.split()].index('1word2')
或者:
def get_abs_pos(lVals, word):
return [i for i,x in enumerate([x for w in l for x in w.split()]) if x == word]
还有最简短的一个:
' '.join(l).split().index('1word2')