python打印列表中低于平均分_如何提取Python列表中一定比例的均匀分布元素?

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)]

In use:

>>> 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]

You could also add round, as int will truncate:

>>> int(3.6)

3

>>> int(round(3.6))

4

If you want to use a proportion rather than a percentage (e.g. 0.5 instead of 50), simply replace 100.0 with 1.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值