Multiply every other element in a list

后端 未结 2 1541
不知归路
不知归路 2021-01-03 16:48

I have a list, let\'s say: list = [6,2,6,2,6,2,6], and I want it to create a new list with every other element multiplied by 2 and every other element multiplie

相关标签:
2条回答
  • 2021-01-03 17:47

    You can use slice assignment and list comprehension:

    l = oldlist[:]
    l[::2] = [x*2 for x in l[::2]]
    

    Your solution is wrong because:

    1. The function doesn't take any arguments
    2. res is declared as a number and not a list
    3. Your loop has no way of knowing the index
    4. You return on the first loop iteration
    5. Not related to the function, but you didn't actually call multi

    Here's your code, corrected:

    def multi(lst):
        res = list(lst) # Copy the list
        # Iterate through the indexes instead of the elements
        for i in range(len(res)):
            if i % 2 == 0:
                res[i] = res[i]*2 
        return res
    
    print(multi([12,2,12,2,12,2,12]))
    
    0 讨论(0)
  • 2021-01-03 17:48

    You can reconstruct the list with list comprehenstion and enumerate function, like this

    >>> [item * 2 if index % 2 == 0 else item for index, item in enumerate(lst)]
    [12, 2, 12, 2, 12, 2, 12]
    

    enumerate function gives the current index of them item in the iterable and the current item, in each iteration. We then use the condition

    item * 2 if index % 2 == 0 else item
    

    to decide the actual value to be used. Here, if index % 2 == 0 then item * 2 will be used otherwise item will be used as it is.

    0 讨论(0)
提交回复
热议问题