[英]How to unpack a single variable tuple in Python3?
I have a tuple-我有一个元组-
('name@mail.com',)
. ('name@mail.com',)
。
I want to unpack it to get 'name@mail.com'.我想解压它以获得'name@mail.com'。
How can I do so?我该怎么做?
I am new to Python so please excuse.我是 Python 的新手,所以请原谅。
The full syntax for unpacking use the syntax for tuple literal so you can use解包的完整语法使用元组文字的语法,因此您可以使用
tu = ('name@mail.com',)
(var,) = tu
The following simplified syntax is allowed允许使用以下简化语法
var, = tu
tu = ('name@mail.com',)
str = tu[0]
print(str) #will return 'name@mail.com'
A tuple is a sequence type, which means the elements can be accessed by their indices.元组是一种序列类型,这意味着可以通过其索引访问元素。
A tuple is just like a list but static, so just do:元组就像一个列表,但 static,所以只需:
('name@mail.com',)[0]
The prettiest way to get the first element and the last element of an iterable
object like tuple
, list
, etc. would be to use the *
feature not same as the *
operator.获取
iterable
object (如tuple
、 list
等)的第一个元素和最后一个元素的最漂亮方法是使用与*
运算符不同的*
功能。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.