0

I have a loop to read in data, but the numbering isn't continuous. Thus, I want to skip specific values. But I only knew how to skip one, not a set of values. This is my example code:

for n in [x for x in range(2,m) if x!=9]:
    if n < 10:
        stationsnr = '00'+np.str(n)
    elif n < 100:
        stationsnr = '0'+np.str(n)
    else:
        stationsnr = np.str(n)

But instead of "x!=9" I need something like if x!= one of those values [9,10,12,16,......] (edit: the values are stored in a list). Any suggestions?

Marek
  • 160
  • 1
  • 2
  • 17
  • Are those values in a list? – Sushant Aug 28 '18 at 18:23
  • https://stackoverflow.com/questions/10149747/and-or-in-python check out this answer – Comp Aug 28 '18 at 18:24
  • Presumably the list comprehension in the `for` loop is just an example? I'd not use a list comprehension there, as that creates a whole list first; use a generator expression at least: `for n in (x for x in range(2, m) if x != 9):` – Martijn Pieters Aug 28 '18 at 18:26
  • @ThatBird That was my plan. – Marek Aug 28 '18 at 18:26
  • Is there some reason you're using `np.str` instead of directly calling the `str` constructor? BTW, you can do that padding without using `if...elif...else`. See `str.zfill` and `str.rjust`. – PM 2Ring Aug 28 '18 at 18:31

3 Answers3

5

You can test if the value is a member of a set:

[... if x not in {9, 10, 12, 16, }]

Set membership testing is O(1) constant time (so fast!).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You can use the enumerate() function in your for loop. It returns the element of the list like normal, but also returns the index position. For example:

indices_to_avoid = [1,4,6]  # indices to skip over
for item, idx in enumerate(range(2, m)):
    if idx not in indices_to_avoid:
        do_something()

Like the above answers said, you can also use a list comprehension, but if you have a long list of exclusions, the list comprehension can get lengthy. I think lengthy list comprehensions are difficult to read and can confuse more than a simple for loop, especially if the list comp goes onto the next line.

Keshinko
  • 318
  • 1
  • 11
0

You could use -

if x is not in [your list]

But it'd be better to use a set than a list because the look-up time on sets is O(1), which is constant, since they're hashed.

So your code could become -

if x is not in (your set)

Also, the append time for list is O(N) while for set is O(1) so inserting to a set will also be faster (and removing from it too)

Sushant
  • 3,499
  • 3
  • 17
  • 34