【发布时间】:2019-07-19 14:58:07
【问题描述】:
我有一个 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吗? -
你想删除列表中的整数做什么?
标签: python python-3.x python-2.7 while-loop itertools