【问题标题】:How to unpack a single variable tuple in Python3?如何在 Python3 中解压单个变量元组?
【发布时间】:2020-10-21 14:20:37
【问题描述】:

我有一个元组-

('name@mail.com',).

我想解压它以获得“name@mail.com”。

我该怎么做?

我是 Python 新手,请见谅。

【问题讨论】:

  • 如果它总是只有一个元素,你可以使用indices 来获取元素。 t[0] 其中 t 是你的元组
  • 您打算如何处理这些内容?它总是单一大小的元组吗?
  • 如果您是新手,最好按照教程进行操作,而不是在 Stack Overflow 上提出您想到的所有问题。主要的 Python 网站提供了一个教程,涵盖了相当多的内容:docs.python.org/3/tutorial/index.html 这里特别介绍了元组:docs.python.org/3/tutorial/…

标签: python python-3.x string tuples


【解决方案1】:

元组就像一个列表,但它是静态的,所以这样做:

('name@mail.com',)[0]

【讨论】:

    【解决方案2】:
    tu = ('name@mail.com',)
    
    str = tu[0]
    
    print(str) #will return 'name@mail.com'
    

    元组是一种序列类型,这意味着元素可以通过它们的索引来访问。

    【讨论】:

      【解决方案3】:

      解包的完整语法使用元组文字的语法,因此您可以使用

      tu = ('name@mail.com',)
      (var,) = tu
      

      允许使用以下简化语法

      var, = tu
      

      【讨论】:

      • 尽管这个问题看起来很简单,但实际上“解包”与只选择第一个索引不同,所以我会选择这个作为实际答案,因为它回答了标题要求的内容. (即使 OP 可能不是故意的)
      【解决方案4】:

      获取iterable 对象(如tuplelist 等)的第一个元素和最后一个元素的最漂亮方法是使用与* 运算符不同的* 功能。

      my_tup = ('a', 'b', 'c',)
      
      # Last element
      *other_els, last_el = my_tup
      
      # First element
      first_el, *other_els = my_tup
      
      # You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:]
      
      # Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. 
      # This will result in no exceptions if you have only 1 element in the tuple.
      my_tup = ('a',)
      
      # This still works
      # Last element
      *other_els, last_el = my_tup
      
      # First element
      first_el, *other_els = my_tup
      
      # other_els is [] here
      
      

      【讨论】:

      • ('a') 不是元组,它解析为'a'。一个元素的元组是('a',)。但很高兴知道,*other_els, last_el = 'a' 也在工作。
      • 我忘了在最后加上,。请不要使用('a'),即使你认为你得到了正确的结果,这是不对的。由于字符串是可切片的,*rest, target 列表爆炸语法可以正常工作。但是如果你使用像('abc')这样的更长的字符串,这将导致rest = ['a', 'b']target = 'c'
      猜你喜欢
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多