【问题标题】:how to change numbers in specific position inside list [closed]如何更改列表内特定位置的数字[关闭]
【发布时间】:2020-12-13 00:36:26
【问题描述】:
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)

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

【问题讨论】:

  • 你在问什么?我不明白你的问题。 “专业的方式”是什么意思?
  • 你想做什么?是否需要在所有偶数位置字符串中乘以 2
  • 您可以借助索引甚至想要更改的数字(您想更改)进行更改
  • print(num) 添加 return num 之后,您会将新值列表放入 x 变量中
  • 你最好不要调用你的函数id(这是一个内置函数),并且不要再次调用你的函数参数。

标签: python arrays list replace element


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

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

    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))) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2019-03-30
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      相关资源
      最近更新 更多