简体   繁体   English

从输入生成第n个值的列表

[英]Generate list with every nth value from input

I had the following code: 我有以下代码:

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

I changed it to only print every nth row: 我将其更改为仅每第n行打印一次:

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? 有没有更多的pythonic方式来编写此代码,以达到相同的结果?

use enumerate and modulo on the index in a modified list comprehension to filter the ones dividable by n : 在修改后的列表推导中对索引使用enumerate和modulo来过滤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. 列表理解过滤是好的,但是在这种情况下,建议直接使用索引的eduffy答案更好,因为索引是直接计算的。 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: 进一步改善此答案:最好使用itertools.islice这样就不会生成临时列表:

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. itertools.islice(points,None,None,n)等效于points[::n]但执行延迟计算。

The list slicing syntax takes an optional third argument to define the "step". 列表切片语法采用可选的第三个参数定义“步骤”。 This take every 3rd in a list: 这需要列表中的每3个:

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

您可以对列表理解使用enumerate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM