我正在编写一个程序,我需要从python中的list
中打乱string
的字母。比如我有这样的list
string
S:有没有什么办法在Python中争夺字符串?
l = ['foo', 'biology', 'sequence']
我想是这样的:
l = ['ofo', 'lbyoogil', 'qceeenus']
什么是做到这一点的最好方法是什么?
感谢您的帮助!
我正在编写一个程序,我需要从python中的list
中打乱string
的字母。比如我有这样的list
string
S:有没有什么办法在Python中争夺字符串?
l = ['foo', 'biology', 'sequence']
我想是这样的:
l = ['ofo', 'lbyoogil', 'qceeenus']
什么是做到这一点的最好方法是什么?
感谢您的帮助!
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']
+1电池!小心他们也不是普通的9v。 – 2011-05-31 03:46:54
列表理解可能不总是最好的方法,生成器表达式或映射可能会更好。我这个例子,我会去'map()'。 – Johnsyweb 2011-05-31 04:31:25
您可以使用random.shuffle:
>>> import random
>>> x = "sequence"
>>> l = list(x)
>>> random.shuffle(l)
>>> y = ''.join(l)
>>> y
'quncesee'
>>>
从这里就可以建立一个函数来完成你想要的。
import random
words = ['foo', 'biology', 'sequence']
words = [''.join(random.sample(word, len(word))) for word in words]
像那些在我面前,我会使用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']
参见:包括
http://stackoverflow.com/questions/1735561/oneliner-scramble-program – trutheality 2011-05-30 22:40:38