我想从许多收藏中选择15张图片。图像的数量取决于该集合中图像的比例。
我的代码是:

image_counts = [16, 2, 14]
total_images = 0
for i in image_counts:
    total_images += i
proportions = [1.0 * i / total_images for i in image_counts]
counts = [int( round( 15 * i)) for i in proportions]

但是由于四舍五入的缘故,输出值加起来是16如何得到一个加起来正好是15的列表?

最佳答案

你的选择之一是:

image_counts = [16, 2, 14]
total_images = sum(image_counts)

proportions = [1.0 * i / total_images for i in image_counts]
counts = [int(15 * i) for i in proportions]
if sum(counts) < 15:
    counts[counts.index(min(counts))] += 1

要完成此答案:
counts[counts.index(min(counts))] += 15 - sum(counts[1:]) # from user1654936

并将最后的列表截断为15个元素。

关于python - 进行比例采样,无不良采样,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12329192/

10-12 21:59