[英]How to take tuple as an argument and returns a tuple consisting of the first three and the last three elements of the argument
In a function, I need to return a tuple consisting the first 3 and last 3 elements of the argument.在 function 中,我需要返回一个包含参数的前 3 个和后 3 个元素的元组。 I have tried the min and max but i need to get (10,20,30,70,80,90)我已经尝试过最小值和最大值,但我需要得到 (10,20,30,70,80,90)
so for example:例如:
if the function is called with the tuple (0,10,20,30,40,50,60,70,80,90) as argument, the function supposed to return (10,20,30,70,80,90).如果使用元组 (0,10,20,30,40,50,60,70,80,90) 作为参数调用 function,则 function 应该返回 (10,200,30,90,8) . Can someone please explain to me or give me a hint on what should I do?有人可以向我解释或提示我该怎么做吗?
this is my current code:这是我当前的代码:
def first3_last3(t):
return min(t), max(t)
t = (10,20,30,40,50,60,70,80,90)
print(first3_last3(t))
You can also use the splat operator *
to merge the sliced tuples:您还可以使用 splat 运算符*
来合并切片元组:
def first3_last3(t):
return (*t[:3], *t[-3:])
t = (10,20,30,40,50,60,70,80,90)
print(first3_last3(t))
Output: Output:
>> (10, 20, 30, 70, 80, 90)
Sorting (if it's unsorted) and using slicing gives you the output you are looking for.排序(如果未排序)并使用切片为您提供您正在寻找的 output。
def first3_last3(t):
t = sorted(t)
return tuple(t[:3] + t[-3:])
t = (10,20,30,40,50,60,70,80,90)
print(first3_last3(t))
returns返回
(10, 20, 30, 70, 80, 90)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.