1

I had the following code:

return [p.to_dict() for p in points]

I changed it to only print every nth row:

n = 100
count = 0

output = []

for p in points:
    if (count % n == 0):
        output.append(p.to_dict())
    count += 1
return output

Is there a more pythonic way to write this, to acheive the same result?

1
  • What is points? Can you provide some data / reproducible code? Commented Apr 17, 2018 at 11:29

3 Answers 3

5

use enumerate and modulo on the index in a modified list comprehension to filter the ones dividable by n:

return [p.to_dict() for i,p in enumerate(points) if i % n == 0]

List comprehension filtering is good, but in that case, eduffy answer which suggests to use slicing with a step is better since the indices are directly computed. Use the filter part only when you cannot predict the indices.

Improving this answer even more: It's even better to use itertools.islice so not temporary list is generated:

import itertools
return [p.to_dict() for p in itertools.islice(points,None,None,n)]

itertools.islice(points,None,None,n) is equivalent to points[::n] but performing lazy evaluation.

Sign up to request clarification or add additional context in comments.

1 Comment

you forgot enumerate :)
5

The list slicing syntax takes an optional third argument to define the "step". This take every 3rd in a list:

 >>> range(10)
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> range(10)[::3]
 [0, 3, 6, 9]

Comments

0

you can use enumerate with list comprehension.

[p.to_dict()  for i, p in enumerate(points) if i %100 == 0]

Comments

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.