In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to define and use tuples in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Define and use tuples
In Python, a tuple is also a sequence of elements in a certain order. The difference between a tuple and a list is that a tuple is an immutable type, which means that once a variable of a tuple type is defined, the elements can no longer be added or deleted, and the value of the element cannot be modified. Defining tuples usually uses () literal syntax, and tuple types support the same operators as lists. The following code demonstrates the definition and operation of tuples.
# define a triple
T1 = (30,10,55)
# define a quad
T2 = ('Luo Hao', 40, True, 'Chengdu, Sichuan')
# View the type of variable
Print (type (T1), type (T2)) #
# View the number of elements in the tuple
Print (len (T1), len (T2)) # 3 4
# get the elements in the tuple through index operation
Print (T1 [0], T1 [- 3]) # 30 30
Print (T2 [3], T2 [- 1]) # Chengdu, Sichuan
# iterate through the elements in the tuple
For member in t2:
Print (member)
# member operation
Print (100 in T1) # False
Print (40 in T2) # True
# stitching
T3 = T1 + T2
Print (T3) # (30,10,55, 'Luo Hao', 40, True, 'Chengdu, Sichuan')
# slicing
Print (T3 [:: 3]) # (30, 'Luo Hao', 'Chengdu, Sichuan')
# comparison operation
Print (T1 = = T3) # False
Print (T1 > = T3) # False
Print (T1)
< (30, 11, 55)) # True 一个元组中如果有两个元素,我们就称之为二元组;一个元组中如果五个元素,我们就称之为五元组。需要提醒大家注意的是,()表示空元组,但是如果元组中只有一个元素,需要加上一个逗号,否则()就不是代表元组的字面量语法,而是改变运算优先级的圆括号,所以('hello', )和(100, )才是一元组,而('hello')和(100)只是字符串和整数。我们可以通过下面的代码来加以验证。 # 空元组 a = () print(type(a)) # # 不是元组 b = ('hello') print(type(b)) # c = (100) print(type(c)) # # 一元组 d = ('hello', ) print(type(d)) # e = (100, ) print(type(e)) # 元组的应用场景 讲到这里,相信大家一定迫切的想知道元组有哪些应用场景,我们给大家举几个例子。 例子1:打包和解包操作。 当我们把多个用逗号分隔的值赋给一个变量时,多个值会打包成一个元组类型;当我们把一个元组赋值给多个变量时,元组会解包成多个值然后分别赋给对应的变量,如下面的代码所示。 # 打包 a = 1, 10, 100 print(type(a), a) # (1, 10, 100) # 解包 i, j, k = a print(i, j, k) # 1 10 100 在解包时,如果解包出来的元素个数和变量个数不对应,会引发ValueError异常,错误信息为:too many values to unpack(解包的值太多)或not enough values to unpack(解包的值不足)。 a = 1, 10, 100, 1000 # i, j, k = a # ValueError: too many values to unpack (expected 3) # i, j, k, l, m, n = a # ValueError: not enough values to unpack (expected 6, got 4) 有一种解决变量个数少于元素的个数方法,就是使用星号表达式,我们之前讲函数的可变参数时使用过星号表达式。有了星号表达式,我们就可以让一个变量接收多个值,代码如下所示。需要注意的是,用星号表达式修饰的变量会变成一个列表,列表中有0个或多个元素。还有在解包语法中,星号表达式只能出现一次。 a = 1, 10, 100, 1000 i, j, *k = a print(i, j, k) # 1 10 [100, 1000] i, *j, k = a print(i, j, k) # 1 [10, 100] 1000 *i, j, k = a print(i, j, k) # [1, 10] 100 1000 *i, j = a print(i, j) # [1, 10, 100] 1000 i, *j = a print(i, j) # 1 [10, 100, 1000] i, j, k, *l = a print(i, j, k, l) # 1 10 100 [1000] i, j, k, l, *m = a print(i, j, k, l, m) # 1 10 100 1000 [] 需要说明一点,解包语法对所有的序列都成立,这就意味着对字符串、列表以及我们之前讲到的range函数返回的范围序列都可以使用解包语法。大家可以尝试运行下面的代码,看看会出现怎样的结果。 a, b, *c = range(1, 10) print(a, b, c) a, b, c = [1, 10, 100] print(a, b, c) a, *b, c = 'hello' print(a, b, c) 现在我们可以反过来思考一下函数的可变参数,可变参数其实就是将多个参数打包成了一个元组,可以通过下面的代码来证明这一点。 def add(*args): print(type(args), args) total = 0 for val in args: total += val return totaladd(1, 10, 20) # (1, 10, 20) add(1, 2, 3, 4, 5) # (1, 2, 3, 4, 5)例子2:交换两个变量的值。 交换两个变量的值是编程语言中的一个经典案例,在很多编程语言中,交换两个变量的值都需要借助一个中间变量才能做到,如果不用中间变量就需要使用比较晦涩的位运算来实现。在Python中,交换两个变量a和b的值只需要使用如下所示的代码。 a, b = b, a 同理,如果要将三个变量a、b、c的值互换,即b赋给a,c赋给b,a赋给c,也可以如法炮制。 a, b, c = b, c, a 需要说明的是,上面并没有用到打包和解包语法,Python的字节码指令中有ROT_TWO和ROT_THREE这样的指令可以实现这个操作,效率是非常高的。但是如果有多于三个变量的值要依次互换,这个时候没有直接可用的字节码指令,执行的原理就是我们上面讲解的打包和解包操作。 例子3:让函数返回多个值。 有的时候一个函数执行完成后可能需要返回多个值,这个时候元组类型应该是比较方便的选择。例如,编写一个找出列表中最大值和最小的函数。 def find_max_and_min(items): """找出列表中最大和最小的元素 :param items: 列表 :return: 最大和最小元素构成的二元组 """ max_one, min_one = items[0], items[0] for item in items: if item >Max_one:
Max_one = item
Elif item < min_one:
Min_one = item
Return max_one, min_one
There are two values in the return statement of the above function, which are assembled into a binary and returned. So you get this tuple by calling the find_max_and_min function, and you can assign two values in the tuple to two variables if you like.
Comparison of tuples and lists
There is also a question worth exploring. Why do you need tuples when you already have list types in Python? This question seems to be a little difficult for beginners, but it doesn't matter. Let's put forward our point of view first. We can learn it while we learn.
Tuples are immutable types, and immutable types are more suitable for multithreaded environments because they reduce the synchronization overhead of concurrent access variables. On this point, we will discuss in detail when we explain multithreading later.
Tuples are immutable types, and immutable types are usually superior to their corresponding mutable types in terms of creation time and footprint. We can use the getsizeof function of the sys module to check how much memory is consumed by tuples and lists that hold the same element. We can also use the timeit function of the timeit module to see how long it takes to create tuples and lists that hold the same elements, as shown below.
Import sys
Import timeit
A = list (range (100000))
B = tuple (range (100000))
Print (sys.getsizeof (a), sys.getsizeof (b)) # 900120 800056
Print (timeit.timeit ('[1, 2, 3, 4, 5, 6, 7, 8, 9])
Print (timeit.timeit ((1, 2, 3, 4, 5, 6, 7, 8, 9))
Tuples and lists in Python can be converted to each other, and we can do this through the following code.
# convert tuples to lists
Info = ('Luo Hao', 175, True, 'Chengdu, Sichuan')
Print (list (info)) # ['Luo Hao', 175, True, 'Chengdu, Sichuan']
# convert lists to tuples
Fruits = ['apple',' banana', 'orange']
Print (tuple (fruits)) # ('apple',' banana', 'orange') "how to define and use tuples in Python" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.