我有一个python列表,我需要花些时间。我正在输出为['fd', 'dfdf', 'keyword', 'ssd', 'sdsd']
但我需要获取['3=', 'fd', 'dfdf', 'keyword', 'ssd', 'sdsd', ';']
from itertools import takewhile, chain
l = [1, 2, "3=", "fd", "dfdf", "keyword", "ssd", "sdsd", ";", "dds"]
s = "keyword"
# get all elements on the right of s
right = takewhile(lambda x: ';' not in x, l[l.index(s) + 1:])
# get all elements on the left of s using a reversed sublist
left = takewhile(lambda x: '=' not in x, l[l.index(s)::-1])
# reverse the left list back and join it to the right list
subl = list(chain(list(left)[::-1], right))
print(subl)
# ['fd', 'dfdf', 'keyword', 'ssd', 'sdsd']
最佳答案
takewhile
的问题是要获得满足条件的元素。
您可以尝试一下(如果我正确理解了您的问题)
l = [1, 2, "3=", "fd", "dfdf", "keyword", "ssd", "sdsd", ";", "dds"]
it = iter(l)
first_index = next(i for i, item in enumerate(it)
if isinstance(item, str) and '=' in item)
last_index = next(i for i, item in enumerate(it, start=first_index+1)
if isinstance(item, str) and ';' in item)
print(l[first_index:last_index + 1])
这将创建一个迭代器
it
(这样就不会再次检查根据拳头条件检查过的item
)。其余的应该很简单。
this answer可能也有帮助。