代码之家  ›  专栏  ›  技术社区  ›  BCS

Getting one value from a python tuple

  •  117
  • BCS  · 技术社区  · 14 年前

    Is there a way to get one value from a tuple in python using expressions?

    def Tup():
      return (3,"hello")
    
    i = 5 + Tup();  ## I want to add just the three
    

    我知道我能做到:

    (j,_) = Tup()
    i = 5 + j
    

    但这会给函数增加几十行,使其长度加倍。

    2 回复  |  直到 6 年前
        1
  •  162
  •   David Z    14 年前

    你可以写

    i = 5 + Tup()[0]
    

    元组可以像列表一样被索引。

    The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

        2
  •  38
  •   Hasnep    6 年前

    对于将来想要得到答案的人,我想对这个问题给出一个更清楚的答案。

    # for making a tuple
    
    MyTuple = (89,32)
    MyTupleWithMoreValues = (1,2,3,4,5,6)
    
    # to concatinate tuples
    AnotherTuple = MyTuple + MyTupleWithMoreValues
    print AnotherTuple
    
    # it should print 89,32,1,2,3,4,5,6
    
    # getting a value from a tuple is similar to a list
    firstVal = MyTuple[0]
    secondVal = MyTuple[1]
    
    # if you have a function called MyTupleFun that returns a tuple,
    # you might want to do this
    MyTupleFun()[0]
    MyTupleFun()[1]
    
    # or this
    v1,v2 = MyTupleFun()
    

    希望这能为某些人扫清障碍。