How do I create a list of random numbers without duplicates?

前端 未结 17 2506
灰色年华
灰色年华 2020-11-22 13:30

I tried using random.randint(0, 100), but some numbers were the same. Is there a method/module to create a list unique random numbers?

Note: The fol

17条回答
  •  甜味超标
    2020-11-22 13:42

    This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.

    import random
    random.sample(range(100), 10)
    

    With reference to your specific code example, you probably want to read all the lines from the file once and then select random lines from the saved list in memory. For example:

    all_lines = f1.readlines()
    for i in range(50):
        lines = random.sample(all_lines, 40)
    

    This way, you only need to actually read from the file once, before your loop. It's much more efficient to do this than to seek back to the start of the file and call f1.readlines() again for each loop iteration.

提交回复
热议问题