Question

When creating a dictionary from a list, i use

for i in range(10):
    random.shuffle(list)
    print "".join(list)

that way i get 10 different random combinations of the list, but if the list has 10 strings, each random i get will have 10 strings, like so:

>>> list
['1', 'n', 'f', 'g', 'z', 'j', '5', 's', '2', '3']
>>> for i in range(5):
...    random.shuffle(list)
...    print "".join(list)
... 
13jgzs25nf
15zngs2jf3
jgfsn3z251
g3sf512zjn
5nsj3fg21z

however, i only want random combinations compiled from, lets say, only 5 out of the 10 strings in the list, how do i go about doing that?

ty!

==========================

@volatility
in an attempt to use what you showed me but try to get a full list like i did in my question i did this:

>>> lst=["1","2","3","f","s","g","5","n","z","j"]
>>> for i in range(10):
...     random.sample(list, 3)
...     print "".join(list)
... 
['5', '2', 'n']
gj5nfs231z
['n', '5', '1']
gj5nfs231z
['z', '3', 'j']
gj5nfs231z
['5', 'g', 'n']
gj5nfs231z
['g', 'z', '2']
gj5nfs231z
['2', '3', 'f']
gj5nfs231z
['g', '2', '5']
gj5nfs231z
['3', 'n', '2']
gj5nfs231z
['g', 'z', '2']
gj5nfs231z
['n', 's', 'g']
gj5nfs231z

which is progress i guess? what i would ultimately like to get would be an input that looks like this (if i used the above list)

52n
z3j
5gn
23f
g25
3n2
gz2
nsg

is that doable?

Was it helpful?

Solution

You can use random.sample for that:

>>> lst = ['1', 'n', 'f', 'g', 'z', 'j', '5', 's', '2', '3']
>>> import random
>>> random.sample(lst, 5)
['f', 's', '3', 'z', 'n']

To get the output you want, you can simply put it inside a for loop:

>>> for i in range(10):
...    print ''.join(random.sample(lst, 5))
...
jn513
13g2f
nfsj5
nj3s1
3zn51
sgj2f
5ns3g
sg51z
23j1z
n2g53

Side note: don't use list as a variable name - it shadows the built-in list type.

OTHER TIPS

Use slice notation.

>>> lst = ['1', 'n', 'f', 'g', 'z', 'j', '5', 's', '2', '3']
>>> random.shuffle(lst)
>>> lst[:5]
['n', 'j', 's', 'z', 'f']
>>> ''.join(lst[:5])
'njszf'

BTW, don't use list as a variable name. It shadows builtin function list.


>>> lst = ['1', 'n', 'f', 'g', 'z', 'j', '5', 's', '2', '3']
>>> for i in range(10):
...     random.shuffle(lst)
...     print ''.join(lst[:5])
...
s3f52
f351s
gnz5j
g2s5n
g3n51
g2fsj
532jf
3f1ng
jnfg5
z35sn
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top