我是 Python 的初学者,对使用 Python 编写脚本非常感兴趣。
最近遇到一个情况,需要获取[-10,+10]范围内的所有整数组合,依次放入两个数组中,也就是说我有数组[A]和[B],在[A] ],我需要让第一个元素为[-10],第二个[-10],然后在[B]中为[-10,-10],然后我将删除元素并制作[A]有 [-10,-10] 但 [B] 有 [-10, -9],那么下一个是 [A] = [-10,-10], [B] = [-10,-8]。 .. 直到最后一个 [A] = [10,10], [B] = [10,10]。所以我做了 4 层 for 循环来实现:
import numpy as np
A = np.zeros((1,2))
B = np.zeros((1,2))
for i in range(-10,+10+1):
A[0][0] = I
for ii in range(-10,+10+1):
A[0][1] = ii
for iii in range(-10,+10+1):
B[0][0] = iii
for iV in range(-10,+10+1):
B[0][1] = iV
以愚蠢的方式按顺序生成 [A] 和 [B] 效果很好。但是,如果我想更改 [A] 和 [B] 的大小,例如 A = np.zeros((1,3)),我应该怎么做而不是添加更多 for 循环行?是否有控制不同层的for循环数的功能?非常感谢。希望我已经把我的问题说清楚了,哈哈。
最好的事物
恩晓
最佳答案
您可能想试试 itertools
图书馆:
from itertools import combinations_with_replacement
for combination in combinations_with_replacement(range(-10,11), n): # n being 4 in your case
A[0] = combination[:n//2]
B[0] = combination[n//2:]
combinations_with_replacement
生成 n
的元组给定数字的所有可能组合中的数字(范围从 -10 到 10);这可以分成两半([:n//2]
-> 前半部分,[n//2:]
-> 后半部分)并分配给您的数组。
关于python - 如何控制for循环层数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63028281/