在python中打印takewhile前后的字符

2024-06-28 19:39:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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']

Tags: therightchaingetonelementsallleft
1条回答
网友
1楼 · 发布于 2024-06-28 19:39:34

^{}的问题是获取满足条件的元素。你知道吗

你可以试试这个(如果我正确理解你的问题)

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也可能有用。你知道吗

相关问题 更多 >