【问题标题】:Fast generating sequences with conditions in Python [duplicate]在Python中快速生成带有条件的序列[重复]
【发布时间】:2021-01-05 15:59:58
【问题描述】:

我正在寻找 [a, b, c] 形式的数字序列的所有组合,其中 a,b,c 可以从集合 (0,1,2) 中取值并满足每个下一个元素大于或等于前一个元素。当然我可以用动物的方式来做,比如:

import itertools

for i in itertools.product(range(0,3), repeat=3):
    if i[0]<=i[1] and i[1]<=i[2]:
        print (i)

输出:

(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 1)
(0, 1, 2)
(0, 2, 2)
(1, 1, 1)
(1, 1, 2)
(1, 2, 2)
(2, 2, 2)

但是,我想比猴子更聪明,因为我实际上会处理更大的序列。如何在保持逐步组合生成结构的同时做得更好?

【问题讨论】:

  • @Grismar 这根本不会产生 OP 想要的东西。它完全忽略了 OP 询问的条件。最重要的是......他们已经在使用产品了!
  • 是的,我不知道combinations_with_replacement()函数:)

标签: python python-3.x sequence


【解决方案1】:

我认为您可以使用 itertools 中的另一个函数来完成这项工作:

import itertools

t = [0,1,2]
comb = itertools.combinations_with_replacement(t, 3)

for c in comb:
    print(c)

【讨论】:

  • 这就是我要找的 :) 谢谢
猜你喜欢
  • 2016-09-04
  • 2020-01-22
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2011-05-26
  • 2019-11-20
相关资源
最近更新 更多