relati的绝对位置

2024-04-20 15:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个单词字符串的Python列表,如何获得给定单词在整个列表中的绝对位置,而不是字符串中的相对位置?在

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

提前谢谢。在


Tags: 字符串列表indexabs单词relsplitequals
3条回答

你需要做的就是把你的发电机安置好:

>>> 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函数(我的新个人爱好)。在

不确定你的绝对位置是什么意思,请看下面我的样本:

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

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

或者:

^{pr2}$

最短的那个:

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

我想你的意思是:

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

相关问题 更多 >