three argument filtering

Lets assume I have defined function:

def threeArgs(x,y,z):
  return ... # Returns True or False

I also have a list of elements:

a = [elem1, elem2, ..., elemN]

I would like to construct another list b containing first and last element form list a and those elements Xn in between for which threeArgs(Xn-1,Xn, Xn+1) returns true.

How to do it in elegant pythonic way?

Answers


Use slicing to create three shifted lists, then zip them together:

[a[0]] + [y for x, y, z in zip(a, a[1:], a[2:]) if threeArgs(x, y, z)] + [a[-1]]

Need Your Help

Autopostback not updating updatePanels in IE6

asp.net ajax

having an issue supporting IE6 (meh)..

How to stop ASP.Net website throwing HttpUnhandledException exception while browsing forward/back through paged listing of items?

asp.net exception-handling website httpunhandledexception

I have an ASP.Net hosted website which displays a list of results as a DataGrid or ASP.Net Repeater with paging of results.

Linq to Entities, Table per Type and Nullable Foreign Key Relationships

linq entity-framework linq-to-entities table-per-type

I'm using Linq to entities applying a Table per Type approach. This has been going very well, up to now. I have the following setup: