1

I have a random csv file containing random numbers, comma separated. I'm doing some iteration, in order to filter data

if (int(row[0]) + i == int(row[1])) and int(row[1]) + i == int(row[2]) and int(row[2]) + i == int(row[3]) and int(row[3]) + i == int(row[4]):
    do something
elif (int(row[0]) + i == int(row[1])) and int(row[1]) + i == int(row[2]) and int(row[2]) + i == int(row[3]):
    do something

The If statements are so much more than that. My code obviously works perfectly, since there's nothing special about it.

I just wish to find a way to do what I'm doing without having to type

if row[0] and row[1] and row[2] and...

say the maximum is row[4] as shown in the example above,basically, i want to something, like a recursive function to do:

for n in range of 0 to 4
    if row[n] +i == row[n+1]:
        do something
        row[n] == row[n-1]
           if row[n-1] ...

I'm not quite sure how to do this, I hope my question is clear. I think this is a similar question in C#.

The part that I don't really know how to do, is how to get rid of and, I mean if i should write if... and ...and then I could just copy paste and do what I was doing, I want a better solution, if it exists.

If a solution exists, I'd prefer if it's a recursive one, because I am working hard to get rid of loops in my code.

4
  • 2
    if all(int(row[n])+i==int(row[n+1]) for n in range(4)): ... Commented Jun 30, 2015 at 20:24
  • 2
    "If a solution exists, I'd prefer if it's a recursive one, because I am working hard to get rid of loops in my code." Why? Recursion is not one of python's strong suits. Generally you'd want to go the other way: remove recursion and replace it with an iterative approach. Commented Jun 30, 2015 at 20:28
  • Are you trying to see if everything in a particular row has the same value? Commented Jun 30, 2015 at 20:30
  • Are you primarily looking for a solution for checking a particular length of row values, like your example with 4, or to find out how many values in a row have this property? Commented Jun 30, 2015 at 20:31

1 Answer 1

1

You can compare with a range:

if [int(x) for x in row[0:4]] == range(int(row[0]), int(row[0]) + 4 * i, i):

The right-hand side will be integers in the range from row[0] through row[0] + 3 * i, in increments of i.

If you're always treating these rows as integers, it might be simpler to convert your row into a list of int beforehand:

row = [int(x) for x in row]

So that you can write the condition more simply:

if row[0:4] == range(row[0], row[0] + 4 * i, i):
Sign up to request clarification or add additional context in comments.

1 Comment

if [int(x) for x in row[0:4]] == range(int(row[0]), int(row[0]) + 4 * i, i):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.