繁体   English   中英

Python返回交换的序列的第一项和最后一项

[英]Python returns first and last item of a sequence exchanged

我需要创建一个对序列进行切片的函数,以便交换第一项和最后一项,并且中间部分停留在中间。 它需要能够处理字符串/列表/元组。 我遇到TypeError错误-无法添加列表+整数。

这个:

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

欢迎任何提示/建议。 想法是适当地切片以便处理不同的对象类型。

尝试这个:

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 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 swap(l):
     temp = l[0]
     l[0] = l[-1]
     l[-1] = temp
     return l

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM