空列表的随机填充

时间:2020-02-18 14:13:18

标签: python

我必须用Python编写一个程序,在其中给出一个范围和许多选择以追加2个空列表,因此该程序的方法应如下所示:

可以选择的范围: 10

提供选择的数量: 5

我应该得到:

随机选择的数字列表:[2,3,7,1,8]

未选择的号码列表: [4,6,5,9,10]

数字不能重复,也不应该存在于两个列表中

我有此代码:

import random
selected_list=[]
not_selected=[]
selecting_number=int(input('give range to select from : '))
select_num=int(input('give number of selections: '))
if selecting_number<select_num:
    print('error')
elif selecting_number>=select_num:
    for x in range(select_num):
        selected_list.append(random.randint(1,select_num))
    print(f'List of numbers selected randomly: {selected_list}')
    if not_selected not in selected_list:
        for y in range(select_num):
            not_selected.append(random.randint(1,select_num))
    print(f'List of numbers not selected previously: {not_selected}')

这是输出

List of numbers selected randomly: [6, 7, 7, 7, 7]

List of numbers not selected: [2, 4, 4, 8, 5]

2 个答案:

答案 0 :(得分:1)

导致错误的原因是random独立地选择随机数,并且由于它们是随机的,有时同一数字被多次拾取。

要解决此问题,您可以使用random.sample(the_list_to_pick_from, number_to_pick) 从文档中:

返回从总体序列中选择的唯一元素的列表 或设置。用于随机抽样而无需替换。

一个实现是这样的:

import random

range_to_pick_from = list(range(1,10))
selected = random.sample(x, 5)
not_selected = [a for a in range_to_pick_from if a not in selected]
print(selected,not_selected)

not_selected也可以写为传统的for循环:

not_selected = []
for num in range_to_pick_from:
    if num not in selected:
        not_selected.append(num)

Documentation for random.sample

答案 1 :(得分:0)

您可以创建一个函数来经常复制该函数并输入参数。

import random

def make_random_lists(my_range=10, selections=5):
    """
    Generate two lists of random numbers.

    INPUT
    ------
      my_range - (int)  how large the range we are selecting from
      selections - (int)  how many numbers should be in the list select list

    OUTPUT
    ------

      s - (list) the selected numbers
      ns - (list) not selected numbers
    """
    # make sure input values are valid
    if (selections < my_range):
        return "selections must be less than range", None
    if my_range <= 0:
        return "range must be larger than 0", None

    total_numbers = set(range(1, my_range+1))  # make range
    s = random.sample(total_numbers, k=selections)  # get selections
    ns = total_numbers - set(s)  # find those not used

    return s, list(ns)

除非您要在每次运行中复制结果,否则无需设置seed。使用集更新列表只是实现此处执行操作的另一种方法!您甚至可以结合使用线条来使内容更简洁,但这有助于使其更加清晰。

调用此函数将产生以下结果:

selected, not_selc = make_random_lists(12, 4) 
print(selected) 
print(not_selc)

>>>[7, 5, 3, 4]
>>>[1, 2, 6, 8, 9, 10, 11, 12]

文档