2 回答
TA贡献1812条经验 获得超5个赞
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)
TA贡献1757条经验 获得超8个赞
如果您只是想更改某些特定位置的值,那么您做事的方式并没有什么特别的错误。当然,这里有一个你可以利用的模式:
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)))
添加回答
举报