【问题标题】:Are there any ways to scramble strings in python?有没有办法在python中打乱字符串?
【发布时间】:2011-09-05 02:17:38
【问题描述】:

我正在编写一个程序,我需要在 python 中从list 中打乱strings 的字母。例如,我有一个 liststrings 之类的:

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

我想要这样的东西:

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

最好的方法是什么?

感谢您的帮助!

【问题讨论】:

标签: python string list scramble


【解决方案1】:

你可以使用random.shuffle:

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

从这里你可以建立一个函数来做你想做的事。

【讨论】:

    【解决方案2】:

    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()
    【解决方案3】:
    import random
    
    words = ['foo', 'biology', 'sequence']
    words = [''.join(random.sample(word, len(word))) for word in words]
    

    【讨论】:

      【解决方案4】:

      和我之前的那些一样,我会使用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']
      

      另见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-29
        • 1970-01-01
        • 2023-03-27
        • 2021-10-29
        • 2010-12-05
        • 2021-10-04
        相关资源
        最近更新 更多