2024-04-20 15:17:30 发布
网友
假设我有一个单词字符串的Python列表,如何获得给定单词在整个列表中的绝对位置,而不是字符串中的相对位置?在
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1'] rel_0word2 = l[0].split().index('1word2') # equals 2 abs_0word2 = ??? # equals 5
提前谢谢。在
你需要做的就是把你的发电机安置好:
>>> 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函数(我的新个人爱好)。在
chain
不确定你的绝对位置是什么意思,请看下面我的样本:
l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1'] print [x for w in l for x in w.split()].index('1word2')
或者:
最短的那个:
' '.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
你需要做的就是把你的发电机安置好:
或者,如果你想用迭代器(也许你在处理很多长字符串或其他东西),你可以尝试使用
chain
函数(我的新个人爱好)。在不确定你的绝对位置是什么意思,请看下面我的样本:
或者:
^{pr2}$最短的那个:
我想你的意思是:
相关问题 更多 >
编程相关推荐