你如何选择“x"?Python中列表中唯一数字的数量?

编程入门 行业动态 更新时间:2024-10-17 09:44:47
本文介绍了你如何选择“x"?Python中列表中唯一数字的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要从列表中挑选出x"个非重复的随机数.例如:

all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15]

如何选择像 [2, 11, 15] 而不是 [3, 8, 8] 这样的列表?

解决方案

这正是 random.sample() 确实如此.

>>>随机样本(范围(1、16)、3)[11, 10, 2]

编辑:我几乎可以肯定这不是您所要求的,但我被迫包含此评论:如果您想从中抽取样本的总体包含重复项,则必须将其删除第一:

population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]人口 = 集合(人口)样本 = random.sample(人口,3)

I need to pick out "x" number of non-repeating, random numbers out of a list. For example:

all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15]

How do I pick out a list like [2, 11, 15] and not [3, 8, 8]?

解决方案

That's exactly what random.sample() does.

>>> random.sample(range(1, 16), 3) [11, 10, 2]

Edit: I'm almost certain this is not what you asked, but I was pushed to include this comment: If the population you want to take samples from contains duplicates, you have to remove them first:

population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] population = set(population) samples = random.sample(population, 3)

更多推荐

你如何选择“x"?Python中列表中唯一数字的数量?

本文发布于:2023-11-30 16:07:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何选择   数量   数字   列表中   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!