tags:

views:

69

answers:

3

I would like to slice random letters from a string.

Given s="howdy"

I would like to pick elements from 's' without replacement but keep the index number.

For example

>>> random.sample(s,len(s))
['w', 'h', 'o', 'd', 'y']

is close to what I want, but I would actually prefer something like

[('w',2), ('h',0), ('o',1), ('d',3), ('y',4)]

with letter-index pairs. This is important because the same letter appears in 's' more than once. ie) "letter" where 't' appears twice but I need to distinguish the first 't' from the second.

Ideally I actually only need to generate/pick letters as I need them but scrambling and calculating all the letters at once (ie: in a list as shown above) is ok.

+10  A: 
>>> random.sample(list(enumerate(a)), 5)
[(1, 'o'), (0, 'h'), (3, 'd'), (2, 'w'), (4, 'y')]
interjay
+5  A: 

You could just enumerate the list before sampling:

>>> random.sample(list(enumerate(l)), 5)
[(1, 'o'), (2, 'w'), (0, 'h'), (3, 'd'), (4, 'y')]
miles82
+2  A: 

It's probably easier to do something like this:

def sample_with_indices(s):
    indices = range(len(s))
    random.shuffle(indices)
    return [(s[i], i) for i in indices]

This will basically shuffle all the indices for a string and then just return the character at that index. Going from character to index is a little more difficult.

Daniel DiPaolo
I was going to suggest something similar, but you ought to use the `list(enumerate(s))` trick above: `return random.shuffle(list(enumerate(s)))`
jemfinch
Yeah, the only benefit this really provides is if you instead want to do something funky with picking which indices you want to use instead and then you could do that followed by the last two lines here.
Daniel DiPaolo