[英]how to iterate and extract data from a list in python 2.7
僅當列表包含特定的初始元素時,如何從列表中提取元素
這里是清單數據= [10,16,2,45,52,12,0,0,2,0,54,85,23,15,48,78,45,16,16,0,4,16 , 3,16,2,0,....]
示例數據: -
1) [10,16,2,45,52,12,0,0,2,0,78,45,16,16,0,4,16,3,16,2,0,....] (upto 200bytes)
2) [16,2,24,14,45,25,87,89,23,0,0,5,10,16,0,4,16,3,16,2,0,....]
3) [11,12,24,14,45,25, 16,2, 121,45,0,10,16,0,4,16,3,16,2,0,....]
首先,我必須尋找元件16,2和提取16,2后的所有元素,直到它找到的元件16,圖3和丟棄之后,每一個重復幀
根據數據流,初始字節可以在列表的開頭,也可以從流中的任何位置開始
您可以使用zip
函數創建對並獲取開始和結束對的索引,使用切片來提取預期的元素:
>>> def extracter(lst,start,end):
... pairs = zip(lst,lst[1:])
... start_index = pairs.index(tuple(start))+2
... end_index = pairs.index(tuple(end))
... return lst[start_index:end_index]
...
演示:
>>> lst = [10, 16,2, 45,52,12,0,0,2,0,78,45,16,16,0,4, 16,3, 16,2,0]
>>> extracter(lst,(16,2),(16,3))
[45, 52, 12, 0, 0, 2, 0, 78, 45, 16, 16, 0, 4]
這應該是相當有效的,雖然有點冗長
from itertools import islice
def n_grams(a, n):
z = (islice(a, i, None) for i in range(n))
return zip(*z)
def filterStartStop(lst, start, stop):
it = n_grams(lst, 3)
for i in it:
if i[0:2] == start:
break
for i in it:
if i[1:3] == stop:
break
yield i[1]
a = range(10)
print(list(filterStartStop(a, (1,2), (7,8))))
>>[3, 4, 5, 6]
與@Kasramvd解決方案相比。
a = range(10**5)
start = (100, 101)
stop = (12345,12346)
%timeit list(filterStartStop(a, start, stop))
%timeit list(extracter(a, start, stop))
b = list(filterStartStop(a, start, stop))
c = list(extracter(a, start, stop))
print (all(i == j for i,j in zip(b,c)))
>>100 loops, best of 3: 6.18 ms per loop
>>100 loops, best of 3: 19.4 ms per loop
>>True
我想我找到了解決方案。
def findIn(l):
foundBeginning=False
foundEnding=False
for i in range(len(l)):
if l[i] == 16:
if l[i+1] == 2:
if foundBeginning == False and foundEnding == False:
begin = i+2
foundBeginning = True
if l[i+1] == 3:
if foundBeginning == True and foundEnding == False:
end = I
foundEnding = True
return(l[begin:end])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.