Want to choose multiple random numbers from a given list of numbers in python
<p>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:</p>

<pre><code>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
</code></pre>

<p>The code gives me the following result:</p>

<pre><code>c=['4','2','3','8']
d=['1','9','5','4']
</code></pre>

<p>But I want the answer as:</p>

<pre><code>c=['4','5','6','7']
d=['9','2','7','1']
</code></pre>

<p>or</p>

<pre><code>c=['5','6','7','8']
d=['7','1','6','5']
</code></pre>

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

<pre><code>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]
</code></pre>

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

<pre><code>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)
</code></pre>

python python-2.7 random