简体   繁体   English

用指定的数字制作所有数字,python

[英]make all number with Specified digits,python

in python, I want to get all n-digit numbers with digits 1 to n (n <10, each exactly once).在 python 中,我想获取所有 n 位数字,数字为 1 到 n (n <10,每个恰好一次)。 How can I ??我怎样才能 ??

Can similar things be done?可以做类似的事情吗? thanks谢谢

You can use itertools.permutations() to get the digits of each number, and then use map() with str() and int() to turn the generated digits into the desired numbers:您可以使用itertools.permutations()来获取每个数字的数字,然后使用map()str()int()将生成的数字转换为所需的数字:

import itertools

n = 3
for item in itertools.permutations(range(1, n + 1), n):
    result = int(''.join(map(str, item)))
    print(result)

This outputs (only first three / last three lines shown):此输出(仅显示前三行/后三行):

123
132
213
231
312
321

Just use itertools.permutations只需使用itertools.permutations

import itertools

n = 3
for item in itertools.permutations(range(1, n + 1), n):
    print(*item, sep='')
    # In case you want to do something with the integer value:
    result = int(''.join(map(str, item)))

Output:输出:

123
132
213
231
312
321

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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