如何避免在Python中将重复元素分配给列表?

时间:2016-05-16 08:55:19

标签: 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

3 个答案:

答案 0 :(得分:5)

您可以使用random.sample,因此无需进行任何过滤:

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

答案 1 :(得分:0)

将您的列表作为一组启动。 Set只能包含唯一值。完成工作后,将您的设置更改回列表。

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了解详情。

答案 2 :(得分:0)

如果看起来可以使用random模块,random可以为您的用例提供非常方便的功能

from random import sample as pick_questions
来自sample提示

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