[英]How to take tuple as an argument and returns a tuple consisting of the first three and the last three elements of the argument
在 function 中,我需要返回一個包含參數的前 3 個和后 3 個元素的元組。 我已經嘗試過最小值和最大值,但我需要得到 (10,20,30,70,80,90)
例如:
如果使用元組 (0,10,20,30,40,50,60,70,80,90) 作為參數調用 function,則 function 應該返回 (10,200,30,90,8) . 有人可以向我解釋或提示我該怎么做嗎?
這是我當前的代碼:
def first3_last3(t):
return min(t), max(t)
t = (10,20,30,40,50,60,70,80,90)
print(first3_last3(t))
您還可以使用 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:
>> (10, 20, 30, 70, 80, 90)
排序(如果未排序)並使用切片為您提供您正在尋找的 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))
返回
(10, 20, 30, 70, 80, 90)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.