如何更改列表中特定位置的数字

how to change numbers in specific position inside list

def id(id):
    num = [int(x) for x in str(id)]
    num[1] = num[1]*2
    num[3] = num[3]*2
    num[5] = num[5]*2
    num[7] = num[7]*2
    print(num)

x = id(123456789)

我已经尝试了很多方法来以“专业的方式”编写这段代码,但这是我让它工作的唯一方法

def multiply_even_indexes(number):
    # Going for each digit, and multiply by 2 if it's index is even
    # int(d)*2**(i % 2) means that we:
    # 1. Convert x to number
    # 2. Multiply x with 2 in the power of either 0 or 1 (depends if `i` is even)
    #    That means:
    #    For i = 1: We get i%2==1 (reminder of 1) so it's multiply by 2^1=2 (so we multiply by two the second element)
    #    For i = 2: We get i%2==0 (mo reminder) so it's multiply by 2^0=1 (so we don't change the third element)
    digits_result = [int(d)*2**(i % 2) for i, d in enumerate(str(number))]
    return digits_result 

x = multiply_even_indexes(123456789)

# [1, 4, 3, 8, 5, 12, 7, 16, 9]
print(x)

如果您只是想更改某些特定位置的值,那么您做事的方式并没有什么特别的错误。当然,这里有一个你可以利用的模式:

for i in range(1, len(num), 2):
    num[i] *= 2

然而,如果位置是任意的,“专业”的方法不是在函数中使用幻数,而是像这样:

POSITIONS = [1, 4, 5, 7]

def make_id(input_id): # don't shadow built-in names
    num = map(int, str(input_id))
    for i in POSITIONS:
        num[i] *= 2
    # return some value, don't just print it
    return int(''.join(map(str, num)))