用指定数字制作所有数字,Python

发布于 2025-02-10 10:47:33 字数 76 浏览 1 评论 0原文

在Python中,我想获得所有n位数字,数字1至n(n< 10,每个n位数字)。我怎么能?

可以做类似的事情吗? 谢谢

in python, I want to get all n-digit numbers with digits 1 to n (n <10, each exactly once). How can I ??

Can similar things be done?
thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

停顿的约定 2025-02-17 10:47:33

您可以使用itertools.permutations()获取每个数字的数字,然后使用map()str()int()< / code>将生成的数字转换为所需数字:

import itertools

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

此输出(仅显示前三行 /最后三行):

123
132
213
231
312
321

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:

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
败给现实 2025-02-17 10:47:33

只需使用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)))

输出:

123
132
213
231
312
321

Just use 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文