【问题标题】:Multiply every other element in a list将列表中的所有其他元素相乘
【发布时间】:2014-10-19 15:40:57
【问题描述】:

我有一个列表,比方说:list = [6,2,6,2,6,2,6],我希望它创建一个新列表,其中每个其他元素乘以 2,每个其他元素乘以 1(保持不变)。 结果应该是:[12,2,12,2,12,2,12]

def multi():
    res = 0
    for i in lst[0::2]:
        return i * 2 

print(multi)

也许是这样,但我不知道如何继续前进。我的解决方案哪里错了?

【问题讨论】:

    标签: python list


    【解决方案1】:

    您可以使用切片分配和列表推导:

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

    您的解决方案是错误的,因为:

    1. 该函数不接受任何参数
    2. res 被声明为数字而不是列表
    3. 您的循环无法知道索引
    4. 您在第一次循环迭代时返回
    5. 与功能无关,但您实际上并没有调用multi

    这是您的代码,已更正:

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

    【讨论】:

      【解决方案2】:

      你可以用列表理解和enumerate函数重构列表,像这样

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

      enumerate 函数在每次迭代中给出可迭代项和当前项的当前索引。然后我们使用条件

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

      决定要使用的实际值。在这里,if index % 2 == 0 然后item * 2 将被使用,否则item 将按原样使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2017-04-06
        • 2022-06-17
        相关资源
        最近更新 更多