我需要创建一个对序列进行切片的函数,以便交换第一项和最后一项,并且中间部分停留在中间。它需要能够处理字符串/列表/元组。我遇到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,)
欢迎任何提示/建议。想法是适当地切片以便处理不同的对象类型。
答案 0 :(得分:4)
尝试一下:
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)
答案 1 :(得分: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[0]
return print([first]+mid+[last])
请注意,它实际上为您提供了一个列表,即[5,2,3,4,1]
,而不是元组(5,2,3,4,1)
。
答案 2 :(得分:0)
您可以使用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
答案 3 :(得分:0)
您可以交换元素
def swap(l):
temp = l[0]
l[0] = l[-1]
l[-1] = temp
return l