简体   繁体   中英

Is there more elegant way for this type of permutations?

I have this code:

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

I want all characters. If I want use this code I should write something like this:

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

Isn't there a more elegant way?

You can just use a string instead of a list of strings. Additionally, you can use the string module and use the predefined constant ascii_lowercase for all lowercase letters:

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

If you want additional characters you can just grow the string to include the characters you want or you can use one of the other string constants defined in the string module:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM