I'm writing a program and I need to scramble the letters of string
s from a list
in python. For instance I开发者_StackOverflow社区 have a list
of string
s like:
l = ['foo', 'biology', 'sequence']
And I want something like this:
l = ['ofo', 'lbyoogil', 'qceeenus']
What is the best way to do it?
Thanks for your help!
Python has batteries included..
>>> from random import shuffle
>>> def shuffle_word(word):
... word = list(word)
... shuffle(word)
... return ''.join(word)
A list comprehension is an easy way to create a new list:
>>> 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]
You can use random.shuffle:
>>> import random
>>> x = "sequence"
>>> l = list(x)
>>> random.shuffle(l)
>>> y = ''.join(l)
>>> y
'quncesee'
>>>
From this you can build up a function to do what you want.
Like those before me, I'd use 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']
See also:
map()
A little bit of styling added, but it does the job!
import random
import os
from colorama import Style, Fore
import colorama
from click import pause
import time
colorama.init()
def main(word):
x = word
l = list(x)
random.shuffle(l)
y = ''.join(l)
print(Fore.YELLOW + ' [>] Output: ' + y + Style.RESET_ALL)
#time.sleep(1)
pause(Fore.RED + Style.BRIGHT + '\n [!] Press any key to exit...' + Style.RESET_ALL)
if __name__ == '__main__':
os.system('cls')
print(Fore.GREEN + Style.BRIGHT + '======= Input Scrambler =======\n' + Style.RESET_ALL)
word = input(Fore.CYAN + ' [>] Input: ')
print(Style.RESET_ALL)
main(word)
精彩评论