Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中有没有办法对字符串进行置乱?_Python_String_List_Scramble - Fatal编程技术网

在python中有没有办法对字符串进行置乱?

在python中有没有办法对字符串进行置乱?,python,string,list,scramble,Python,String,List,Scramble,我正在编写一个程序,我需要在python中从列表中对字符串s的字母进行置乱。例如,我有一个list的strings,比如: l = ['foo', 'biology', 'sequence'] 我想要这样的东西: l = ['ofo', 'lbyoogil', 'qceeenus'] 最好的方法是什么 谢谢你的帮助 您可以使用random.shuffle: >>> import random >>> x = "sequence" >>>

我正在编写一个程序,我需要在python中从
列表
中对
字符串
s的字母进行置乱。例如,我有一个
list
string
s,比如:

l = ['foo', 'biology', 'sequence']
我想要这样的东西:

l = ['ofo', 'lbyoogil', 'qceeenus']
最好的方法是什么


谢谢你的帮助

您可以使用random.shuffle:

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

从这里,您可以构建一个函数来做您想做的事情。

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。列表理解可能并不总是最好的方法,生成器表达式或映射可能更好。在这个例子中,我会选择
map()
import random

words = ['foo', 'biology', 'sequence']
words = [''.join(random.sample(word, len(word))) for word in words]
>>> 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']