这种类型的排列有更优雅的方式吗?

3 python permutation python-3.x

我有这个代码:

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

我想要所有字符。如果我想使用这段代码,我应该写这样的东西:

variations = list(itertools.permutations(['a', 'b', 'c', 'd', 'e', '.......
Run Code Online (Sandbox Code Playgroud)

没有更优雅的方式吗?

ssh*_*124 6

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

import string
variations = itertools.permutations(string.ascii_lowercase, 2)
Run Code Online (Sandbox Code Playgroud)

如果你想要额外的字符,你可以只增加字符串以包含你想要的字符,或者你可以使用string 模块中定义的其他字符串常量之一:

...permutations(string.ascii_lowercase + '/\\$!@#%', 2)
...permutations(string.printable, 2)
Run Code Online (Sandbox Code Playgroud)

  • `string.printable` 就是你需要的 (6认同)