假设我有一个Python字符串的列表,我如何获得整个列表中给定单词的绝对位置,而不是字符串中的相对位置?相对的绝对位置
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
rel_0word2 = l[0].split().index('1word2') # equals 2
abs_0word2 = ??? # equals 5
在此先感谢。
假设我有一个Python字符串的列表,我如何获得整个列表中给定单词的绝对位置,而不是字符串中的相对位置?相对的绝对位置
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
rel_0word2 = l[0].split().index('1word2') # equals 2
abs_0word2 = ??? # equals 5
在此先感谢。
不知道你指的是绝对位置是什么,请找我的示例如下:
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')
使用string.find
,可以在文档here中查看。
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']
index = l[0].find('0word2')
所有你需要做的就是嵌套你的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
功能(我新的个人收藏) 。
我想你指的是以下几点:
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
下面是基于迭代求解的备选答案:
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
没有这么一个班轮,漂亮的发电机,但它完全不需要构建一个大长表。
不要让称为`l`的变量。它看起来太接近`1`。 – 2011-08-17 11:00:22
更好的是,除非上下文需要它,否则不要创建一个或两个字母变量(例如数学公式)。它使可读性受损。 – Bogdan 2011-08-17 11:14:20
我会争辩说,至少在这种情况下,它可以从上下文中推断出来(因为赋值到文字在Python中是无效的,并且总体上是不合理的),但总的来说,thx是建议。 – SomeOne 2011-08-17 15:17:03