[英]Extracting multiple piece of data in a list between keywords
此代碼提取關鍵字“開始”和“結束”之間的數據(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']
如何提取所有數據而不是僅提取第一部分數據
我同意上面的評論者,這是一個可以做的非常簡單的例子。
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
您可以執行以下操作來獲取商品的索引號,並按照需要使用它們:
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]
“ pythonic”方法是在列表上進行簡單迭代而不處理索引。 這是一個如何完成的示例:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.