简体   繁体   中英

Want to choose multiple random numbers from a given list of numbers in python

In Python how can I choose two or more random numbers from a given list,such that the numbers are chosen in the same sequence they are arranged in the list they are chosen from?It seems random.choice selects only one number from the list per iteration and as stated earlier random.sample does not give satisfactory answers.for example:

import random
a=['1','2','3','4','5','6','7','8']
b=['4','3','9','2','7','1','6','5']
c=random.sample(a,4)
d=random.sample(b,4)
print "c=",c
print "d=",d

The code gives me the following result:

c=['4','2','3','8']
d=['1','9','5','4']

But I want the answer as:

c=['4','5','6','7']
d=['9','2','7','1']

or

c=['5','6','7','8']
d=['7','1','6','5']

Answer for original version of question:

To get two samples randomly, use random.sample . First, lets define a list:

>>> lst = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Now, lets get two samples randomly:

>>> random.sample(lst, 2)
[13, 16]
>>> random.sample(lst, 2)
[10, 12]

Sampling is done without replacement.

Looks like you want four consecutive values starting at a random offset, not four values from anywhere in the sequence. So don't use sample , just select a random start point (early enough to ensure the slice doesn't run off the end of the list and end up shorter than desired), then slice four elements off starting there:

import random

...

selectcnt = 4
cstart = random.randint(0, len(a) - selectcnt)
c = a[cstart:cstart + selectcnt]
dstart = random.randint(0, len(b) - selectcnt)
d = b[dstart:dstart + selectcnt]

You could factor it out to make it a little nicer (allowing you to one-line individual selections):

import random

def get_random_slice(seq, slicelen):
    '''Get slicelen items from seq beginning at a random offset'''
    start = random.randint(0, len(seq) - slicelen)
    return seq[start:start + slicelen]

c = get_random_slice(a, 4)
d = get_random_slice(b, 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM