2024-09-27 07:28:52 发布
网友
我正在编写一个程序,我需要在python中对来自list的strings字母进行置乱。例如,我有一个list的strings类似:
list
string
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']
您可以使用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]
Python包含电池。。
列表理解是创建新列表的简单方法:
您可以使用random.shuffle:
从这里你可以建立一个函数来做你想做的事情。
相关问题 更多 >
编程相关推荐