【问题标题】:Taking from a list of numbers and making a new one从数字列表中获取并创建一个新数字
【发布时间】:2016-09-27 12:55:27
【问题描述】:

问题来了:

给定一个整数列表,使第一个和最后一个整数相加,结果将是新列表的第一个整数,第二个和倒数第二个整数相加,结果将是该新列表的第二个整数,依此类推。如果您的列表是奇数,请将中心编号留在原始列表中。

我遇到了两个问题。我不知道如何让我的代码在获取第一个和最后一个值的同时继续迭代,将其添加到新列表中,然后一直工作到中间。另外,如果它是奇数,我如何让它迭代并停在中间值?

到目前为止,这是我的代码:

myList = [1,2,3,4,5,6]
newList = []

def switch(myList):
    for i in range(len(myList)):
        if len(myList) % 2 == 0:
            firstPart = newList+myList[0:+1]
            secondPart = myList[len(myList)-1:len(myList)+1]
            thirdPart = firstPart + secondPart
            return thirdPart
        else:
            if len(myList) % 2 == 1:

【问题讨论】:

  • 您可能希望咨询this question 以获得简化任务的好方法。

标签: python python-3.x


【解决方案1】:

更新:在经历了所有的压缩、求和、映射、切片和反转之后,这个解决方案让我觉得非常简单,实际上:

def switch(my_list):
    new_list = my_list[:]  # make a copy not to harm the original
    for i in range(len(my_list)//2):   # at the appropriate index ...
        new_list[i] += new_list.pop()  # ... add the element popped from the end
    return new_list

>>> switch([1,1,1,1])
[2, 2]
>>> switch([1,1,1,1,1])
[2, 2, 1]

【讨论】:

  • 我正在使用python 3,但我会尝试一下。
【解决方案2】:
def switch(a_list):
    N = len(a_list)
    HALF = N//2

    new_list = []
    for i in range(HALF):
        j = N-i-1
        new_list.append(a_list[i] + a_list[j])
    if N % 2:
        new_list.append(a_list[HALF])

    return new_list

print(switch([1,2,3,4,5,6]))    # -> [7, 7, 7]
print(switch([1,2,3,4,5,6,7]))  # -> [8, 8, 8, 4]

【讨论】:

    【解决方案3】:
    import itertools
    n=len(myList)
    new_list=[e+f for e, f in itertools.izip(myList[:n/2], reversed(myList)[:n/2])]
    

    myList[:n/2] 提取列表的第一部分 [1,2,3]
    reversed(myList) 反转初始列表 [6,5,4,3,2,1] 然后使用 [:n/2] 截断

    然后可以使用 izip 同时遍历这两个列表,这样就可以轻松地做你想做的事情:

    e,f in itertools.izip([1,2,3], [6, 5,4]) => e,f= (1,6), 然后 (2,5) 然后 (3,4 )

    在奇数长度的情况下,我加个特殊情况:

    if len(myList)%2==1:
        new_list.append(myList[n/2+1])
    

    【讨论】:

    • 看起来很热,但它如何解决偶数/奇数要求?
    • 你能向我解释一下这是做什么的吗?
    • 恕我直言,@schwobaseggl 下面提出的解决方案是最优雅和最 Pythonic 的。
    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 2023-01-17
    • 2022-06-26
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多