【问题标题】:How to change the characters order in a string in python 3.X? [duplicate]如何在 python 3.X 中更改字符串中的字符顺序? [复制]
【发布时间】:2018-05-06 09:22:44
【问题描述】:

假设我得到了 100 个随机单词(甚至不是真正的单词,只是单词)...... 就像“ABCD”一样,我想制作一个程序,它采用我提到的那个词,并以随机顺序打印出这个词的所有选项。 例如单词“ABC”将打印:“ABC”、“BAC”、CAB”、“BCA”、“CBA”。 我可以手动完成,但如果我有 100 个单词,我就不能...... 那么如何编写一个在 python 中执行的代码呢?

【问题讨论】:

  • 听起来你想要itertools.permutations。你想要所有可能的方式来订购这些字母吗?如果是这样,那么对于您的示例,您错过了“ACB”。
  • 是的,我把 acb 弄丢了
  • 第 1 步:创建排列。第 2 步:随机播放。

标签: python string python-3.x random replace


【解决方案1】:

您可以使用 itertools 来做到这一点:

import itertools
import random

words = ['word1', 'word2', 'word3']

for word in words:
    permutations_list = [''.join(x) for x in itertools.permutations(word)]
    random.shuffle(permutations_list)
    print(permutations_list)

【讨论】:

  • 非常感谢你们!
猜你喜欢
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 2016-05-13
相关资源
最近更新 更多