Each for clause can have an associated if filter:
d = [x + y for x in 'test' if x in 'sm' for y in 'TEST' if y in ('P', 'A')] print( d )# w ww. j a v a 2 s .c om d=[x + y + z for x in 'test' if x in 'sm' for y in 'TEST' if y in ('P', 'A') for z in '123' if z > '1'] print( d )
Use attached if selections on nested for clauses:
d = [(x, y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1] print( d )
Here, the code combines even numbers from 0 through 4 with odd numbers from 0 through 4.
The if clauses filter out items in each iteration. Here is the equivalent statement-based code:
res = [] for x in range(5): if x % 2 == 0: for y in range(5): if y % 2 == 1: res.append((x, y)) # from www .j a va2 s . co m print( res )