在python中打印takewhile前后的字符
我有一个python列表,需要在其中执行takewhile。我得到的输出是在python中打印takewhile前后的字符,python,python-3.x,python-2.7,while-loop,itertools,Python,Python 3.x,Python 2.7,While Loop,Itertools,我有一个python列表,需要在其中执行takewhile。我得到的输出是 ['fd','dfdfdf','keyword','ssd','sdsd']但是我需要得到['3=','fd','dfdfdf','keyword','ssd','sdsd',';'] from itertools import takewhile, chain l = [1, 2, "3=", "fd", "dfdf", "keyword", "ssd", "sdsd", ";", "dds"] s = "key
['fd','dfdfdf','keyword','ssd','sdsd']
但是我需要得到['3=','fd','dfdfdf','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
(这样,根据第一个条件检查的项将不会再次检查)
剩下的应该很简单
可能也会有帮助。是否需要使用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])