python - 使用迭代器从 [1, 2, 3] 中获取特定的列表序列

标签 python combinations permutation python-itertools

我想实现这个输出

[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]

从此给定列表:[1,2,3] .

我尝试过使用

foo = [1, 2, 2]
print(list(permutations(foo, 3)))

还有这个

l

ist(it.combinations_with_replacement([1,2,3], 3))

from itertools import combinations 
  
def rSubset(arr, r): 
   
    return list(combinations(arr, r)) 
  
 
if __name__ == "__main__": 
    arr = [1, 2, 3] 
    r = 3
    print (rSubset(arr, r))

但我无法获得所需的结果,请提供帮助

最佳答案

您想要一个产品,而不是排列或组合。

from itertools import product

print(list(product([1,2,3], repeat=3)))

关于python - 使用迭代器从 [1, 2, 3] 中获取特定的列表序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64987503/

相关文章:

python - 无法在 Spark Streaming 作业中导入 kafkaProducer

python - 在Python中递归生成n个选择k个组合的列表 - 但返回一个列表

python - 无需替换数组的快速组合 - NumPy/Python

c++ - 创建变量之间的运算符排列

python - Asyncio - 检查事件循环中是否具有特定参数的协程的方法?

python - 将简单的 python "program"转换为 C "program"!

r - R中按组的组合

arrays - 如何生成多个数组的所有排列/组合?

java - N 个列表的排列

python - 如何使用 Flask-SQLalchemy 从现有表创建类