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

2024-09-27 07:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,我需要在python中对来自liststrings字母进行置乱。例如,我有一个liststrings类似:

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

我想要这样的东西:

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

最好的方法是什么?

谢谢你的帮助!


Tags: 方法程序foo字母listsequencestringsbiology
3条回答

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']

您可以使用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]

相关问题 更多 >

    热门问题