vendredi 23 mars 2018

Efficient list building in Python

Being a long-time Matlab user, I am accustomed to getting a caution whenever I build a list/array/anything with multiple elements in a loop such that it changes size every time, because that slows things down.

As I teach myself Python 2.7, I'm wondering if such a rule applies here to strings. I know exactly how long I want my string to be, and I have a specific list of the characters I want to build it from, but otherwise I want it to be random. My favorite code I've written so far is:

freq = 0.8
seq = '0'*length
for ii in range(length):
    num = np.random.rand(1)
    if num < freq:
        cha = '1'
        seq = seq[:ii] + cha + seq[ii+1:]

I already tried seq[ii] = '1', but, to put it in IPython's words, TypeError: 'str' object does not support item assignment.

So, am I doing this the most Pythonic way, or is there some sleight of hand that I haven't seen yet - maybe a random string or list generator to which I can directly give a list of characters I want it to randomly choose between, the probability I want each possibility to have, and how long I want this string or list to be?

(I've seen other questions about random strings, but while they do address how to make it the right length, they are generally trying to generate passwords, with all ASCII characters being equally likely. That's not what I want.)




Aucun commentaire:

Enregistrer un commentaire