【问题标题】:How to make that multiply all numbers in list (Permutation) with smaller code?如何用更小的代码将列表(排列)中的所有数字相乘?
【发布时间】:2016-10-15 18:52:06
【问题描述】:

我的问题是:

    perm_list = list(range(a,b,-1))
    if len(perm_list) == 1:
       print(perm_list[0])
    elif len(perm_list) == 2:
       print(perm_list[0]* perm_list[1])
    elif len(perm_list) == 3:

如果我能做到的话,我找不到办法让它更小。
因为我会写到 15 次,如果我写 15 次,它会更大,更难写。
如果有更小一点的,你们可以告诉我吗?

【问题讨论】:

  • 请解释您要做什么。你的代码不是很清楚。您没有提供足够的示例来理解您要做什么。第 15 个elif 会是什么样子?
  • 我正在尝试进行排列,就像您将放置 2 个数字 P(a.b)
  • 最大数量为15
  • 如果你把 15 和 2 放在一起,它将是 p(15,2),它应该是 15.14
  • 看起来您只是将列表中的所有项目相乘?

标签: python python-3.x permutation


【解决方案1】:

只需使用itertools

from itertools import permutations
lst = list(range(3))
result = list(permutations(lst, 2))
print(result)
=> [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
print(list(permutations(lst, 3)))
=>  [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多