【问题标题】:Getting one value from a tuple从元组中获取一个值
【发布时间】:2011-03-09 08:11:49
【问题描述】:

有没有办法在 Python 中使用表达式从元组中获取一个值?

def tup():
  return (3, "hello")

i = 5 + tup()  # I want to add just the three

我知道我可以做到:

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

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

【问题讨论】:

  • _ 也只是一个变量。它只是经常用于为它分配可以丢弃的值。但理论上你可以从_获取值

标签: python tuples


【解决方案1】:

你可以写

i = 5 + tup()[0]

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

元组和列表的主要区别在于元组是不可变的——您不能将元组的元素设置为不同的值,也不能像从列表中那样添加或删除元素。但除此之外,在大多数情况下,它们的工作原理几乎相同。

【讨论】:

    【解决方案2】:

    对于将来寻找答案的任何人,我想对这个问题给出一个更清晰的答案。

    # for making a tuple
    my_tuple = (89, 32)
    my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)
    
    # to concatenate tuples
    another_tuple = my_tuple + my_tuple_with_more_values
    print(another_tuple)
    # (89, 32, 1, 2, 3, 4, 5, 6)
    
    # getting a value from a tuple is similar to a list
    first_val = my_tuple[0]
    second_val = my_tuple[1]
    
    # if you have a function called my_tuple_fun that returns a tuple,
    # you might want to do this
    my_tuple_fun()[0]
    my_tuple_fun()[1]
    
    # or this
    v1, v2 = my_tuple_fun()
    

    希望这能为有需要的人进一步澄清问题。

    【讨论】:

    • 感谢您的更新。为了完整起见,您可能希望在元组解包中添加使用下划线作为“虚拟”占位符。
    【解决方案3】:

    一般

    元组a 的单个元素可以以类似索引数组的方式访问-

    通过a[0]a[1],...取决于元组中的元素数量。

    示例

    如果你的元组是a=(3,"a")

    • a[0] 产生3
    • a[1] 产生 "a"

    问题的具体答案

    def tup():
      return (3, "hello")
    

    tup() 返回一个 2 元组。

    为了“解决”

    i = 5 + tup()  # I want to add just the three
    

    你选择了3

    tup()[0|    #first element
    

    总而言之

    i = 5 + tup()[0]
    

    替代方案

    使用 namedtuple,它允许您按名称(和按索引)访问元组元素。详情https://docs.python.org/3/library/collections.html#collections.namedtuple

    >>> import collections
    >>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
    >>> m = MyTuple(3, "hello")
    >>> m[0]
    3
    >>> m.mynumber
    3
    >>> m[1]
    'hello'
    >>> m.mystring
    'hello'
    

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多