2016-05-16 1 views
0

Я пытаюсь написать программу, которая выводит список вопросов для теста. То, что я пытаюсь сделать, заключается в том, чтобы избежать добавления дубликатов в список таким образом, когда я печатаю список, у меня есть только определенное количество уникальных элементов.Как я могу избежать назначения повторяющихся элементов в список в Python?

def pick_questions(input_list, number_of_picks): 
    """Picks random elements of an input list given the number of picks""" 
    selected_strings = [] 

    for index in range(0, number_of_picks + 1): 
     random_index = randint(0, len(input_list) - 1) 

     if input_list[random_index] not in selected_strings: 
      selected_strings.append(input_list[random_index]) 
      random_index = randint(0, len(input_list) - 1) 

    return selected_strings 
+4

Используйте [set] (https://docs.python.org/2/library/stdtypes.html#set). –

+1

@kanayamalakar, should _not_ быть отступом – Holloway

+1

'для индекса в диапазоне (0, number_of_picks + 1):' не хочет, чтобы вы хотели, он дает вам цифры '0, 1, ..., npicks', то есть вы будете у вас есть «npicks + 1» из вашего входного списка. – gboffi

ответ

0

Инициируйте свой список как набор. Набор может содержать только уникальные значения. После завершения работы измените свой набор на список.

set = {1, 2, 3} 
>>> set 
set([1, 2, 3]) 
>>> set.add(4) # this would add 4 to the set because the set does not have 4 
>>> set 
set([1, 2, 3, 4]) 
>>> set.add(4) # this would *not* add 4 to the set because the set already has 4 
>>> set 
set([1, 2, 3, 4]) 
>>> list(set) 
[1, 2, 3, 4] 

для получения более подробной информации обратитесь к this link.

+0

Вы потеряете любой заказ, если вы сохраните элементы таким образом. – Holloway

+1

как @Holloway сказал, это потеряло бы порядок. Если вам нужно сохранить заказ, обратитесь к этому сообщению. http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order –

5

Вы можете использовать random.sample, так что не будет нужно сделать какой-либо фильтрации:

>>> import random 
>>> random.sample(range(10), 5) 
[1, 4, 3, 8, 7] 
0

Если, как это кажется, вы можете использовать random модуль random имеет очень удобную функцию для вашего случая использования

from random import sample as pick_questions 

sample документации «s из YHE ipython оперативного

In [4]: sample? 
Signature: sample(population, k) 
Docstring: 
Chooses k unique random elements from a population sequence or set. 

Returns a new list containing elements from the population while 
leaving the original population unchanged. The resulting list is 
in selection order so that all sub-slices will also be valid random 
samples. This allows raffle winners (the sample) to be partitioned 
into grand prize and second place winners (the subslices). 

Members of the population need not be hashable or unique. If the 
population contains repeats, then each occurrence is a possible 
selection in the sample. 

To choose a sample in a range of integers, use range as an argument. 
This is especially fast and space efficient for sampling from a 
large population: sample(range(10000000), 60) 
File:  ~/src/miniconda3/lib/python3.5/random.py 
Type:  method 
Смежные вопросы