Python: element selection without replacement

I would like to slice random letters from a string.

Given s = "Howda"

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

for example

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

close to what i want but i would prefer something like

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

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

Ideally, I only need to generate / select letters as needed, but scrambling and calculating all the letters at the same time (i.e. in the list, as shown above) is fine.

+7
python
source share
3 answers
 >>> random.sample(list(enumerate(a)), 5) [(1, 'o'), (0, 'h'), (3, 'd'), (2, 'w'), (4, 'y')] 
+16
source share

You can simply list the list before fetching:

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

It is 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 indexes for the string, and then just return the character to that index. The transition from character to index is a bit more complicated.

+3
source share

All Articles