how to create a random array from a list, each value in the array is not duplicate in python

前端 未结 2 1407
野趣味
野趣味 2021-01-29 00:23

so my question is I have a list from 0 - 17 and I want to create a 7 value array in random, in which each value in the array is not duplicate in python?

相关标签:
2条回答
  • 2021-01-29 00:29

    You want random.sample

    In [22]: L
    Out[22]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
    
    In [23]: random.sample(L, 7)
    Out[23]: [6, 7, 2, 16, 10, 0, 3]
    
    0 讨论(0)
  • 2021-01-29 00:54

    Try this:

    import random
    lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
    random.shuffle(lst)
    lst[:7]
    
    0 讨论(0)
提交回复
热议问题