2011-08-17 188 views
2

假設我有一個Python字符串的列表,我如何獲得整個列表中給定單詞的絕對位置,而不是字符串中的相對位置?相對的絕對位置

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

在此先感謝。

+3

不要讓稱爲`l`的變量。它看起來太接近`1`。 – 2011-08-17 11:00:22

+2

更好的是,除非上下文需要它,否則不要創建一個或兩個字母變量(例如數學公式)。它使可讀性受損。 – Bogdan 2011-08-17 11:14:20

+0

我會爭辯說,至少在這種情況下,它可以從上下文中推斷出來(因爲賦值到文字在Python中是無效的,並且總體上是不合理的),但總的來說,thx是建議。 – SomeOne 2011-08-17 15:17:03

回答

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') 
-1

使用string.find,可以在文檔here中查看。

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

所有你需要做的就是嵌套你的g enerators右:

>>> 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功能(我新的個人收藏) 。

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 
0

下面是基於迭代求解的備選答案:

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 

沒有這麼一個班輪,漂亮的發電機,但它完全不需要構建一個大長表。