我有一个python列表,需要在其中执行takewhile。我的输出是
['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']
^{} 的问题是获取满足条件的元素。你知道吗
你可以试试这个(如果我正确理解你的问题)
这将创建一个迭代器
it
(这样,根据第一个条件检查的item
将不会再次检查)。你知道吗剩下的应该很简单。你知道吗
this answer也可能有用。你知道吗
相关问题 更多 >
编程相关推荐