我正在编写一个程序,我需要从python中的string
中搜索list
s的字母。例如,我有一个list
的string
s像:
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']
import random
words = ['foo', 'biology', 'sequence']
words = [''.join(random.sample(word, len(word))) for word in words]
你可以使用random.shuffle:
>>> import random
>>> x = "sequence"
>>> l = list(x)
>>> random.shuffle(l)
>>> y = ''.join(l)
>>> y
'quncesee'
>>>
从这里你可以建立一个功能来做你想要的。
像我之前的那些,我会使用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']
也可以看看: