如何提取Python列表中一定比例的均匀分布的元素? [英] How should a certain percentage of evenly-distributed elements of a Python list be extracted?
问题描述
我有一个数据点列表.对于程序的完整运行,我将使用所有数据点,但是对于代码测试,我只想使用其中的一小部分,以便程序在短时间内运行.但是,我不想简单地获取列表的前n个元素.我想从列表中选择元素的均匀分布.因此,如果我使用50%的数据点,则可能需要每隔两个数据点从数据点列表中进行选择.
I have a list of data points. For the full run of my program, I'll use all of the data points, but for testing of the code, I want to use only a small percentage of them in order that the program run in a short time. I do not want simply to take the first n elements of the list, though; I want to select an even distribution of the elements from the list. So, if I'm using 50% of the data points, I might want to select from the list of data points every second data points.
基本上,我希望有一个函数,该函数将一个列表和一个百分比作为参数,并返回一个列表,该列表由输入列表中元素的均匀分布组成,其数量与请求的百分比尽可能接近.
Basically, I want to have a function that takes as arguments a list and a percentage and returns a list consisting of an even distribution of elements from the input list, the number of which corresponds as closely as possible to the percentage requested.
什么是做到这一点的好方法?
What would be a good way to do this?
推荐答案
这可以通过设置带台阶的切片来简单地实现:
This can trivially be achieved by setting a slice with a step:
def select_elements(seq, perc):
"""Select a defined percentage of the elements of seq."""
return seq[::int(100.0/perc)]
使用中:
>>> select_elements(range(10), 50)
[0, 2, 4, 6, 8]
>>> select_elements(range(10), 33)
[0, 3, 6, 9]
>>> select_elements(range(10), 25)
[0, 4, 8]
您还可以添加round
,因为int
会截断:
You could also add round
, as int
will truncate:
>>> int(3.6)
3
>>> int(round(3.6))
4
如果要使用比例而不是百分比(例如,用0.5
代替50
),只需将100.0
替换为1
.
If you want to use a proportion rather than a percentage (e.g. 0.5
instead of 50
), simply replace 100.0
with 1
.
这篇关于如何提取Python列表中一定比例的均匀分布的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!