python中的增量数组,类似于基数系统

2024-05-12 22:57:37 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个类似于[0 0 0]的数组,我想在一个类似基的尺度上迭代它。假设我选择以100为基数,假设我想用一个小的尾数系统。我的输出如下:
[10 0 0]
[2 0 0 0]

[99 0 0 0]
[0 0 1]

我的代码目前在一个函数'indexArray'中,但是我想知道是否有可能在没有if语句的情况下以一种更简单的方式实现这一点?在

def indexArray(enteredArr):
    enteredArr[0] += 1
    for i in range(len(enteredArr)):
        if enteredArr[i] > 99:
            enteredArr[i] = 0
            enteredArr[i + 1] += 1
    return enteredArr

Tags: 函数代码forif系统def方式情况
2条回答
num = 45
base = 3

num_base = []
remainder = num

# the remainders of the integer divisions of the number by the base are the digits of the number in the new base
# see also here: https://math.stackexchange.com/questions/111150/changing-a-number-between-arbitrary-bases
while remainder:
    num_base.append(remainder % base)
    remainder //= base

# join the list in reverse while changing type of digits to characters
print("".join(str(x) for x in num_base[::-1]))

在Python中,如果您查找它,有一种更简单的方法。在

你的主循环可以是:

for i in itertools.product(range(BASE), repeat=NDIM):
    ... stuff ...

对于您的示例,BASE=100和NDIM=4,但是相同的方法适用于任何其他值。在

i将是一个数组值的元组,就像(0, 0, 0, 0), (0, 0, 0, 1) ... (BASE-1, BASE-1, BASE-1, BASE-1)一样递增。在

相关问题 更多 >