[Python] Tuples

本文介绍了Python中元组的基本概念及应用场景,包括元组的创建、使用、不可变性特点及其与列表的区别。此外,还详细解释了元组解包、多变量赋值以及如何通过函数返回元组。

Python provides another useful built-in type: tuples. Tuples are used to store related pieces of information. Consider this example involving latitude and longitude:

>>> AngkorWat = (13.4125, 103.866667)
>>> print(type(AngkorWat))
<class 'tuple'>
>>> print("Angkor Wat is at latitude: {}".format(AngkorWat[0]))
Angkor Wat is at latitude: 13.4125
>>> print("Angkor Wat is at longitude: {}".format(AngkorWat[1]))
Angkor Wat is at longitude: 103.866667

 

Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indexes (for example AngkorWat[0] and AngkorWat[1]). Unlike lists, tuples are immutable. You can't add and remove items from tuples, or sort them in place. 

 

Why Tuples?

Why do we have tuples if they're like lists with less features? Tuples useful when you have two or more values that are so closely related that they will always be used together, like latitude and longitude coordinates.

Tuples can be used to assign multiple variables in a compact way:

>>> dimensions = 52, 40, 100 
>>> length, width, height = dimensions 
>>> print("The dimensions are {}x{}x{}".format(length, width, height))
The dimensions are 52x40x100
world_heritage_locations = {(13.4125, 103.866667): "Angkor Wat",
                            (25.73333, 32.6): "Ancient Thebes",
                            (30.330556, 35.4433330): "Petra",
                            (-13.116667, -72.583333): "Machu Picchu"}

 

Notice that the values assigned to the tuple dimensions aren't surrounded with parentheses as previous examples were. The parentheses are optional when making tuples, and programmers frequently omit them if parentheses don't clarify the code.

 

Tuple Unpacking

In the second line, three variables are assigned from the content of the tuple dimensions. This is called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into multiple variables without having to access them one by one and make multiple assignment statements.

In this example, if we won't need to use dimensions directly, we could shorten those two lines of code into a single line that assigns three variables in one go!

length, width, height = 52, 40, 100

 

Returning Tuples

def first_and_last(sequence):
    """returns the first and last elements of a sequence"""
    return sequence[0], sequence[-1]

>>> first_and_last(["Spam", "egg", "sausage", "Spam"])
('Spam', 'Spam')

A function that returns a tuple can also be used to assign multiple variables:

>>> start, end = first_and_last(["Spam", "egg", "sausage", "Spam"])
>>> print(start)
Spam
>>> print(end)
Spam
def hours2days(_hours):
    days = _hours//24
    hours = _hours%24
    return days, hours
     
hours2days(24) """(1, 0)"""
hours2days(25) """(1,1)"""
hours2days(10000)  """(416, 16)"""

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值