Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中打印takewhile前后的字符_Python_Python 3.x_Python 2.7_While Loop_Itertools - Fatal编程技术网

在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

我有一个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 = "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])