14

我正在编写一个程序,我需要在 python中打乱strings中的字母。list例如,我有一个listof strings 之类的:

l = ['foo', 'biology', 'sequence']

我想要这样的东西:

l = ['ofo', 'lbyoogil', 'qceeenus']

最好的方法是什么?

谢谢你的帮助!

4

4 回答 4

30

Python包含电池..

>>> from random import shuffle

>>> def shuffle_word(word):
...    word = list(word)
...    shuffle(word)
...    return ''.join(word)

列表推导式是一种创建新列表的简单方法:

>>> L = ['foo', 'biology', 'sequence']
>>> [shuffle_word(word) for word in L]
['ofo', 'lbyooil', 'qceaenes']
于 2011-05-30T22:45:03.963 回答
4
import random

words = ['foo', 'biology', 'sequence']
words = [''.join(random.sample(word, len(word))) for word in words]
于 2011-05-30T22:49:58.977 回答
3

您可以使用 random.shuffle:

>>> import random
>>> x = "sequence"
>>> l = list(x)
>>> random.shuffle(l)
>>> y = ''.join(l)
>>> y
'quncesee'
>>>

从这里你可以建立一个功能来做你想做的事。

于 2011-05-30T22:42:25.357 回答
1

像我之前的那些,我会使用random.shuffle()

>>> import random
>>> def mixup(word):
...     as_list_of_letters = list(word)
...     random.shuffle(as_list_of_letters)
...     return ''.join(as_list_of_letters)
...
>>> map(mixup, l)
['oof', 'iogylob', 'seucqene']
>>> map(mixup, l)
['foo', 'byolgio', 'ueseqcen']
>>> map(mixup, l)
['oof', 'yobgloi', 'enescque']
>>> map(mixup, l)
['oof', 'yolbgoi', 'qsecnuee']

也可以看看:

于 2011-05-30T22:53:35.907 回答