开发者

Absolute position from relative

Provided that I have a Python list of s开发者_开发知识库trings of words, how do I get absolute position of a given word in the whole list, as opposed to relative position within the string?

l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
rel_0word2 = l[0].split().index('1word2') # equals 2
abs_0word2 = ??? # equals 5

Thanks in advance.


Not sure on what you mean on absolute position, please find below my sample:

l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']

print [x for w in l for x in w.split()].index('1word2')

Or:

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]

And the shortest one:

' '.join(l).split().index('1word2')


All you need to do is nest your generators right:

>>> 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

Or if you want to do it with iterators (maybe if you're working with lots of long strings or something), you can try playing around with the chain function (my new personal fav).


I think you mean the following:

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


Here's an alternative answer that is based on an iterative solution:

def find_in_sentences(find_me, sentences):
    i = 0
    for sentence in sentences:
        words = sentences.split()
        if find_me in words:
            return words.index(find_me) + i
        else:
            i += len(words)
    return False

Not quite as one-liner-spiffy as the generator, but it does it all without needing to construct a big long list.


Use string.find, as can be viewed in the docs here.

l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
index = l[0].find('0word2')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜