Python returns 交换了序列的第一项和最后一项

Python returns first and last item of a sequence exchanged

我需要创建一个函数来对序列进行切片,以便交换第一个和最后一个项目并且中间的项目留在中间。它需要能够处理 string/list/tuples。我遇到类型错误问题 - 无法添加 list + int。

这个:

def exchange_first_last(seq):
    """This returns the first and last item of a sequence exchanged"""
    first = seq[-1]
    mid = seq[1:-1]
    last = seq[0]
    return print(first+mid+last)

产生

(5, [2, 3, 4], 1)

但我不想要元组中的列表,只需要一个流动序列。

(5,2,3,4,1,)

任何 hints/suggestions 欢迎。这个想法是正确切片以处理不同的对象类型。

稍微更改一下代码,注意方括号:

def exchange_first_last(seq):
    """This returns the first and last item of a sequence exchanged"""
    first = seq[-1]
    mid = seq[1:-1]
    last = seq[0]
    return print([first]+mid+[last])

请注意,它实际上为您提供了一个 列表,即 [5,2,3,4,1],而不是一个元组 (5,2,3,4,1)

您可以使用 list.extend():

def exchange_first_last(seq):
    """This returns the first and last item of a sequence exchanged"""
    first = seq[-1]
    mid = seq[1:-1]
    last = seq[0]
    merged = []
    merged.extend(first)
    merged.extend(mid)
    merged.extend(last)
    return merged

试试这个:

def exchange_first_last(seq):
    """This returns the first and last item of a sequence exchanged"""
    first = seq[-1:]
    mid = seq[1:-1]
    last = seq[:1]
    return print(first+mid+last)

你可以交换元素

def swap(l):
     temp = l[0]
     l[0] = l[-1]
     l[-1] = temp
     return l