【问题标题】:How to take tuple as an argument and returns a tuple consisting of the first three and the last three elements of the argument如何将元组作为参数并返回由参数的前三个和后三个元素组成的元组
【发布时间】:2020-05-13 11:34:38
【问题描述】:

在一个函数中,我需要返回一个由参数的前 3 个和后 3 个元素组成的元组。我已经尝试过最小值和最大值,但我需要得到 (10,20,30,70,80,90)

例如:

如果使用元组 (0,10,20,30,40,50,60,70,80,90) 作为参数调用函数,则函数应该返回 (10,20,30,70,80 ,90)。有人可以向我解释或提示我该怎么做吗?

这是我当前的代码:

def first3_last3(t):
    return min(t), max(t)


t = (10,20,30,40,50,60,70,80,90)
print(first3_last3(t))

【问题讨论】:

  • 如果您对函数的输入进行排序,则可以使用切片、[:3] 等...

标签: python function tuples


【解决方案1】:

您还可以使用 splat 运算符 * 来合并切片元组:

def first3_last3(t):
    return (*t[:3], *t[-3:])

t = (10,20,30,40,50,60,70,80,90)
print(first3_last3(t))

输出:

>> (10, 20, 30, 70, 80, 90)

【讨论】:

    【解决方案2】:

    排序(如果未排序)并使用切片为您提供所需的输出。

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多