【问题标题】:printing characters before and after takewhile in python在python中在takewhile之前和之后打印字符
【发布时间】: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


【解决方案1】:

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])

这会创建一个迭代器it(这样就不会再次检查已针对第一个条件检查的items)。

其余的应该很简单。

this answer 也可能有帮助。

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    相关资源
    最近更新 更多