在关键字之间的列表中提取多个数据

时间:2017-10-22 00:30:50

标签: python

此代码提取关键词'start'和'end'之间的数据(1,2,3)

some_data = ['a', 2, 'b', 'start', 1, 2, 3, 'end']

start = some_data.index('start')+1
end = some_data.index('end')

for data in some_data[start:end]:
     print(data)

但如果列表中有多个数据,如垃圾行,会发生什么:

['a', 2, 'b', 'start', 1, 2, 3, 'end', 'a', 1, x, 'start', 3,  7, 8, 'end', 'start', 3, 7, 8, 'end']

如何将所有内容提取出来而不仅仅是第一段数据

3 个答案:

答案 0 :(得分:0)

我同意上面的评论者,这是一个可以做什么的非常简单的例子。

some_data = ['a', 2, 'b', 'start', 1, 2, 3, 'end', 'a', 1, 'x', 'start', 3,  7, 8, 'end', 'start', 3, 7, 8, 'end']

index = 0
retrieved_data = []
while index < len(some_data):
    if some_data[index] == 'start':
        collecting = True
        values = []
        while collecting:
            index += 1
            if some_data[index] == 'end':
                collecting = False
            else:
                values.append(some_data[index])
        retrieved_data.append(values)
    index += 1

答案 1 :(得分:0)

你可以做这样的事情来获取项目的索引号,并按照你想要的方式使用它们:

def get_indexes(items, keyword):
    indexes = []
    if keyword in items:
        for i, data in enumerate(items):
            if data == keyword:
                indexes.append(i)
    else:
        raise AttributeError("invalid keyword given")
    return indexes

这将返回具有指定关键字的所有索引的list

some_data = ['a', 2, 'b', 'start', 1, 2, 3, 'end', 'a', 1, 'x', 'start', 3,  7, 8, 'end', 'start', 3, 7, 8, 'end']
get_indexes(some_data, "start")
# [3, 11, 16]
get_indexes(some_data, "end")
# [7, 15, 20]

答案 2 :(得分:-1)

&#34; pythonic&#34;这样做的方法是在列表上进行简单的迭代而不处理索引。以下是如何完成的示例:

def get_intervals(data):
    collecting = False
    intervals = []

    for item in data:
        if item == 'start':
            interval = []
            collecting = True
            continue
        if item == 'end':
            intervals.append(interval)
            collecting = False
            continue
        if collecting:
            interval.append(item)

    return intervals