【问题标题】:Is there more elegant way for this type of permutations?这种排列有更优雅的方法吗?
【发布时间】:2019-12-29 06:19:24
【问题描述】:

我有这个代码:

import itertools
variations = list(itertools.permutations(['a', 'b', 'c'], 2))
for v in variations:
    print(''.join(v))

我想要所有角色。如果我想使用这段代码,我应该这样写:

variations = list(itertools.permutations(['a', 'b', 'c', 'd', 'e', '.......

没有更优雅的方式吗?

【问题讨论】:

  • 为什么要添加list()
  • ['a', 'b', 'c']'abc' 在这里没有不同的输出。
  • 绝对没有必要转换成列表,事实上如果有大量的item会大大增加资源使用率。

标签: python python-3.x permutation


【解决方案1】:

您可以只使用字符串而不是字符串列表。此外,您可以使用string 模块并将预定义的常量ascii_lowercase 用于所有小写字母:

import string
variations = itertools.permutations(string.ascii_lowercase, 2)

如果您需要其他字符,您可以增加字符串以包含您想要的字符,或者您可以使用字符串模块中定义的其他 string constants 之一:

...permutations(string.ascii_lowercase + '/\\$!@#%', 2)
...permutations(string.printable, 2)

【讨论】:

  • string.printable 是你所需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 2022-12-24
  • 2019-03-13
  • 2015-06-22
  • 1970-01-01
相关资源
最近更新 更多