Ryan
Ryan

Reputation: 1072

Elegant way to test list of if statements in Python

I have some spreadsheets represented as a list of lists in python, and I'm generating output from those.

However, I end up with some really ugly code when I have to omit sections of the sheet, such as: if not "string" in currentline[index] and not "string2" in currentline[index] and not... and so on.

Is it possible to represent all the conditions as a list of tuples, say omit = [(0, "foo"), (5,"bar)] and then have one if statement that checks of both statements are false?

If I have these two lists:

list = [["bar","baz","foo","bar"],["foo","bar","baz","foo","bar"]]
omit = [(0,"foo"),(4,"bar")]

and I only want the first one to print, I need an if statement to test every condition inside omit somehow, something like:

for idx, condition in enumerate(omit):
    a, b = omit[idx]
    if list[a] != omit[b] for all pairs of a and b in omit:
        print list

Upvotes: 0

Views: 222

Answers (2)

jwilner
jwilner

Reputation: 6606

Use any and all for dynamically-generated lists of predicates.

They each take an iterable of objects and return whether any or all of them are True -- and they work lazily.

So, for example:

any([False, False, False]) is False
all([True, True, True]) is True
any([False, False, True]) is True

The beautiful part comes when you use 'em with generators.

any(i % 2 == 0 for i in range(50)) is True

Here, you can use these operators with your data structures.

for row in rows:
    if any(row[idx] == omittable for idx, omittable in omit):
        print 'naw uh'

Upvotes: -1

DSM
DSM

Reputation: 353309

You could use any and a generator expression:

>>> seq = [["bar","baz","foo","bar"],["foo","bar","baz","foo","bar"]]
>>> omit = [(0,"foo"),(4,"bar")]
>>> for x in seq:
...     if not any(i < len(x) and x[i] == v for i,v in omit):
...         print(x)
...         
['bar', 'baz', 'foo', 'bar']

The i < len(x) is necessary so that we don't try accessing element #4 in a list that doesn't have one.

This version demands that neither of the omit conditions is met; if you only want to omit sublists if both conditions are met, replace any with all.

Upvotes: 4

Related Questions