在python中递增数组的元素

时间:2018-02-01 22:47:34

标签: python arrays list numpy

我有一个问题,我无法解决与python数组相关的问题:

我有以下数组x = [n1, n2, n3] 我想以下列方式递增它:

while x[0] < R:
   while x[1] < R:
     if np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2) < R:
        x[2] = x[2] + dx           
        counter = counter + 1
     else:

        x[1] = x[1] + dx
        length = dx
print(counter)
x[0] = x[0] + dx
x[1] = dx

此代码将执行以下操作:

  

示例:对于dx=0.1R=1,我们从0.1开始

     

x=[0.1, 0.1, 0.1] 开始(在第一个循环之后)   x=[0.9, 0.1, 0.1]然后[0.1, 0.2, 0.1]依此类推,直至[0.9, 0.9, 0.1]我们将获得[0.1,0.1,0.2]我们将重新开始[0.2, 0.1, 0.2]等等

我想将这个想法扩展到任意数量的维度,但我不知何故被卡住了,任何帮助都会非常感激

1 个答案:

答案 0 :(得分:1)

您可以使用此功能,并调整repeat值:

from itertools import product

values = [x*.1 for x in range(1, 10)]
for X in product(values, repeat=3):
    print(['%.1f' % x for x in X])

# ['0.1', '0.1', '0.1']
# ['0.1', '0.1', '0.2']
# ['0.1', '0.1', '0.3']
# ['0.1', '0.1', '0.4']
#     
# ['0.1', '0.9', '0.9']
# ['0.2', '0.1', '0.1']
# ['0.2', '0.1', '0.2']
# ['0.2', '0.1', '0.3']
# 
# ['0.9', '0.9', '0.7']
# ['0.9', '0.9', '0.8']
# ['0.9', '0.9', '0.9']