gpt4 book ai didi

python - python 中增加数组元素

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:04 24 4
gpt4 key购买 nike

我有一个无法解决的与 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

此代码将执行以下操作:

example: for dx=0.1 and R=1 and we start with 0.1

start with x=[0.1, 0.1, 0.1] (after the first loop)x=[0.9, 0.1, 0.1] And then [0.1, 0.2, 0.1] And so on until [0.9, 0.9, 0.1] After we will get [0.1,0.1,0.2] And we will start again with [0.2, 0.1, 0.2] and so on

我想将这个想法扩展到任意数量的维度,但我不知何故陷入困境,任何帮助将不胜感激

最佳答案

您可以使用它,并调整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']

关于python - python 中增加数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48573004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com