【问题标题】:Setting a range as an argument in itertools.permutations [duplicate]在 itertools.permutations 中将范围设置为参数 [重复]
【发布时间】:2019-05-20 17:19:12
【问题描述】:

我想为以下列表打印长度为 1-4 的所有排列[1,2,3,4]

我知道我可以设置一个 for 循环并将 for 循环索引作为参数传递,但我试图让以下代码工作:

import itertools
nums = [1,2,3,4]
perms = itertools.permutations(nums,range(1,4))
print(list(perms))

希望参数 range(1,4) 能够在字符串长度为 1、2、3 和 4 上运行 intertools.permutations(nums)。

如果可以使用 itertools 表示法做到这一点,有什么想法吗?

是否也可以将长度 = 1 的情况打印为: (1), (2), (3), (4) 不是 (1,), (2,), (3,), (4,)

【问题讨论】:

  • 我相信this 就是您要找的。​​span>
  • 排列的集合与集合的幂集不同。

标签: python


【解决方案1】:

permutations的4个电话串在一起:

from itertools import chain, permutations

nums = [1,2,3,4]
perms = list(chain.from_iterable(permutations(nums, i) for i in range(1,5)))
print(perms)

如果要将 1 元组打印为单独的值,则需要单独处理:

for t in perms:
    if len(t) == 1:
        print("(t[0])")
    else:
        print(t)

如果您关心元组的外观。如果您真的想要一个非元组值,则需要单独提取该值,并记住 1(1)完全相同相同的值。

perms = list(nums,  # permutations(nums, 1) == nums
             chain.from_iterable(permutations(nums, i) for i in range(2,5)))

【讨论】:

  • 有没有办法把 (1,) 改成 (1)....谢谢
【解决方案2】:

你也可以写成生成器表达式:

perms = (it for i in range(1, 4) for it in itertools.permutations(nums,i))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2023-04-05
    • 2017-07-13
    相关资源
    最近更新 更多