2

I have a list like this:

['MAR', 'TFFVGGNFK', 'LNGSK', 'QSIK', 'EIVER', 'LNTASIPENVEVVICPPATYLDYSVSLVK']

That used to be a string. I need to know the position of the first and last element of each string on the list to do something like:

0-2 MAR
3-11 TFFVGGNFK
...

How can i do it?

4

5 回答 5

4

Python 3 解决方案,使用itertools.accumulate

>>> from itertools import accumulate
>>> a = ['MAR', 'TFFVGGNFK', 'LNGSK', 'QSIK', 'EIVER', 'LNTASIPENVEVVICPPATYLDYSVSLVK']
>>> starts = [0] + list(accumulate(map(len, a)))
>>> starts
[0, 3, 12, 17, 21, 26, 55]
>>> pairs = [(l,r-1) for l,r in zip(starts, starts[1:])]
>>> pairs
[(0, 2), (3, 11), (12, 16), (17, 20), (21, 25), (26, 54)]

请记住,由于在 Python 中切片的工作(0,3)方式通常比 更有用(0, 2),但我假设你有你的理由。

于 2013-05-27T15:01:51.140 回答
2

如您所愿,在一种方法中:

from collections import OrderedDict
lst = ['MAR', 'TFFVGGNFK', 'LNGSK', 'QSIK', 'EIVER', 'LNTASIPENVEVVICPPATYLDYSVSLVK']

def indexes(l):
    start = 0
    indexes = OrderedDict()
    for i in l:
        end = start+len(i)-1
        indexes[i] = (start, end)
        start = end+1
    return indexes

print indexes(lst)
>>> 
OrderedDict([('MAR', (0, 2)), ('TFFVGGNFK', (3, 11)), ('LNGSK', (12, 16)), ('QSIK', (17, 20)), ('EIVER', (21, 25)), ('LNTASIPENVEVVICPPATYLDYSVSLVK', (26, 54))])

但是我会将索引更改为没有“偏移量”并删除您在方法中看到的-1and 。+1

于 2013-05-27T15:13:29.787 回答
2
foo = ['MAR', 'TFFVGGNFK', 'LNGSK', 'QSIK', 'EIVER', 'LNTASIPENVEVVICPPATYLDYSVSLVK']

count = 0
for bar in foo:
    newcount = count + len(bar)
    print count, '-', newcount-1, bar
    count = newcount
于 2013-05-27T14:54:36.890 回答
0

尝试这个:

list = ['MAR', 'TFFVGGNFK', 'LNGSK', 'QSIK', 'EIVER', 'LNTASIPENVEVVICPPATYLDYSVSLVK']
lenlist = []
for s in list:
    lenlist.append(len(s))

现在列表lenlist将包含每个字符串的长度。从这里您可以使用for循环来获取开始和结束:

belist = [] # list containing beginning & end
for i in range(len(lenlist)):
    belist.append(0)
    for j in range(i):
        belist[i].append(lenlist[j])
    belist[i] = str(belist[i]) + '-' + str(lenlist[i])

我认为这应该工作:)

顺便说一句,你的开始和结束将由一个分隔-,而不是把它们放在一个列表中,belist[i] = str(belist[i]) + '-' + str(lenlist[i])用. 替换该行belist[i] = (belist[i], lenlist[i])

于 2013-05-27T15:15:15.587 回答
-1

如果我理解正确,您必须加入您的列表:

text = ''.join(myList)

那么,你只需要index它:

pos = text.index("MAR")
value = (pos, pos + len("MAR"))
于 2013-05-27T15:00:14.283 回答