Table of Contents
1. Tuple Creation && Access
(1) Tuple Creation of a group:
(2) Access:
2. Tuple modification && deletion
(1) Tuple modification:
(1) Deletion of tuples:
3. Built-in methods of tuples
4. Decompose the sequence into separate variables
(2)
5.实现优先级队列
Home Backend Development Python Tutorial Detailed explanation of Python tuples with examples

Detailed explanation of Python tuples with examples

Mar 14, 2022 pm 05:46 PM
python

This article brings you relevant knowledge about python, which mainly introduces related issues about tuples, including the creation, access, modification, deletion and built-in methods of tuples, etc. ,I hope everyone has to help.

Detailed explanation of Python tuples with examples

Recommended learning: python tutorial

Introduction - In Python, important data information in the project is saved through data structures . The Python language has a variety of built-in data structures, such as lists, tuples, dictionaries, and sets, etc. In this class, we will talk about one of the most important data structures in Python - tuples.

In Python, we can think of tuples as a special kind of list. The only difference between it and a list is that the data elements in the tuple cannot be changed [this remains unchanged - not only cannot the data items be changed, but also data items cannot be added or deleted! 】. When we need to create a set of immutable data, we usually put the data into tuples~

1. Tuple Creation && Access

(1) Tuple Creation of a group:

In Python, the basic form of creating a tuple is to enclose the data elements in parentheses "()", and separate each element with a comma ",".
is as follows:

tuple1 = ('xiaoming', 'xiaohong', 18, 21)
tuple2 = (1, 2, 3, 4, 5)

# 而且——是可以创建空元组哦!
tuple3 = ()

# 小注意——如果你创建的元组只包含一个元素时,也不要忘记在元素后面加上逗号。让其识别为一个元组:
tuple4 = (22, )
Copy after login

(2) Access:

Tuples are similar to strings and lists. The indexes start from 0 and can be intercepted and summed. Combination and other operations.
is as follows:

tuple1 = ('xiaoming', 'xiaohong', 18, 21)
tuple2 = (1, 2, 3, 4, 5)

# 显示元组中索引为1的元素的值
print("tuple1[1]:", tuple1[0])

# 显示元组中索引从1到3的元素的值
print("tuple2[1:3]:", tuple2[1:3])
Copy after login

Detailed explanation of Python tuples with examples

2. Tuple modification && deletion

(1) Tuple modification:

Although it is said at the beginning that tuples are immutable, it still has a supported operation - connection and combination between tuples:

tuple1 = ('xiaoming', 'xiaohong', 18, 21)
tuple2 = (1, 2, 3, 4, 5)

tuple_new = tuple1 + tuple2
print(tuple_new)
Copy after login

Detailed explanation of Python tuples with examples

(1) Deletion of tuples:

Although tuples are immutable, the entire tuple can be deleted through the del statement.
is as follows:

tuple1 = ('xiaoming', 'xiaohong', 18, 21)

print(tuple1)		# 正常打印tuple1

del tuple1

print(tuple1)		# 因为上面删除了tuple1,所以再打印会报错哦!
Copy after login

Detailed explanation of Python tuples with examples

3. Built-in methods of tuples

Tuples are immutable, but we can pass Use built-in methods to manipulate tuples. Commonly used built-in methods are as follows:

  1. len(tuple): calculates the number of elements in a tuple;
  2. max(tuple): returns the maximum value of elements in a tuple;
  3. min(tuple): Returns the minimum value of the elements in the tuple;
  4. tuple(seq): Converts the list to a tuple.

In fact, more often than not, we convert tuples into lists first, and then convert them into tuples after the operation (because lists have many methods~).

4. Decompose the sequence into separate variables

(1)

Python allows you to separate a tuple or sequence containing N elements into are N separate variables. This is because Python syntax allows any sequence/iterable object to be decomposed into separate variables through a simple assignment operation, the only requirement is that the total number and structure of the variables match the sequence.
is as follows:

tuple1 = (18, 22)
x, y = tuple1
print(x)
print(y)

tuple2 = ['xiaoming', 33, 19.8, (2012, 1, 11)]
name, age, level, date = tuple2
print(name)
print(date)
Copy after login

Detailed explanation of Python tuples with examples

If you want to decompose an iterable object of unknown or arbitrary length, wouldn’t the above decomposition operation be very nice! Usually there are some known components or patterns in this type of iterable object (for example: everything after element 1 is a phone number). After using the "*" asterisk expression to decompose the iterable object, developers can Easily leverage these patterns to get related elements without having to do complex operations in iterable objects.

In Python, the asterisk expression is very useful when iterating over a variable-length sequence of tuples. The following demonstrates the process of decomposing a sequence of tuples to be marked.

records = [
    ('AAA', 1, 2),
    ('BBB', 'hello'),
    ('CCC', 5, 3)
]

def do_foo(x, y):
    print('AAA', x, y)

def do_bar(s):
    print('BBB', s)

for tag, *args in records:
    if tag == 'AAA':
        do_foo(*args)
    elif tag == 'BBB':
        do_bar(*args)

line = 'guan:ijing234://wef:678d:guan'
uname, *fields, homedir, sh = line.split(':')
print(uname)
print(*fields)
print(homedir)
print(sh)
Copy after login

Detailed explanation of Python tuples with examples

(2)

When iteratively processing sequences such as lists or tuples in Python, sometimes you need to count the last few items Record to realize the historical record statistics function.

Using the built-in deque implementation:

from _collections import deque

q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)
q.append(4)
print(q)
Copy after login

Detailed explanation of Python tuples with examples

is as follows - demonstrating the use of the last few items in the sequence as a historical record process.

from _collections import deque

def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)

    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
    with open('123.txt') as f:
        for line, prevlines in search(f, 'python', 5):
            for pline in prevlines:	# 包含python的行
                print(pline)  # print (pline, end='')
            # 打印最后检查过的N行文本
            print(line)  # print (pline, end='')
Copy after login

123.txt:

pythonpythonpythonpythonpythonpythonpython

python


python
Copy after login

Detailed explanation of Python tuples with examples

在上述代码中,对一系列文本行实现了简单的文本匹配操作,当发现有合适的匹配时,就输出当前的匹配行以及最后检查过的N行文本。使用deque(maxlen=N)创建了一个固定长度的队列。当有新记录加入而使得队列变成已满状态时,会自动移除最老的那条记录。当编写搜索某项记录的代码时,通常会用到含有yield关键字的生成器函数,它能够将处理搜索过程的代码和使用搜索结果的代码成功解耦开来。

5.实现优先级队列

使用内置模块heapq可以实现一个简单的优先级队列。
如下——演示了实现一个简单的优先级队列的过程。

import heapq
class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]

class Item:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return 'Item({!r})'.format(self.name)

q = PriorityQueue()
q.push(Item('AAA'), 1)
q.push(Item('BBB'), 4)
q.push(Item('CCC'), 5)
q.push(Item('DDD'), 1)
print(q.pop())
print(q.pop())
print(q.pop())
Copy after login

在上述代码中,利用heapq模块实现了一个简单的优先级队列,第一次执行pop()操作时返回的元素具有最高的优先级。
拥有相同优先级的两个元素(foo和grok)返回的顺序,同插入到队列时的顺序相同。

函数heapq.heappush()和heapq.heappop()分别实现了列表_queue中元素的插入和移除操作,并且保证列表中的第一个元素的优先级最低。

函数heappop()总是返回“最小”的元素,并且因为push和pop操作的复杂度都是O(log2N),其中N代表堆中元素的数量,因此就算N的值很大,这些操作的效率也非常高。

上述代码中的队列以元组 (-priority, index, item)的形式组成,priority取负值是为了让队列能够按元素的优先级从高到底排列。这和正常的堆排列顺序相反,一般情况下,堆是按从小到大的顺序进行排序的。变量index的作用是将具有相同优先级的元素以适当的顺序排列,通过维护一个不断递增的索引,元素将以它们加入队列时的顺序排列。但是当index在对具有相同优先级的元素间进行比较操作,同样扮演一个重要的角色。

在Python中,如果以元组(priority, item)的形式存储元素,只要它们的优先级不同,它们就可以进行比较。但是如果两个元组的优先级相同,在进行比较操作时会失败。这时可以考虑引入一个额外的索引值,以(priority, index, item)的方式建立元组,因为没有哪两个元组会有相同的index值,所以这样就可以完全避免上述问题。一旦比较操作的结果可以确定,Python就不会再去比较剩下的元组元素了。

如下——演示了实现一个简单的优先级队列的过程:

import heapq
class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]

class Item:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return 'Item({!r})'.format(self.name)

# ①
a = Item('AAA')     
b = Item('BBB')
#a <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/49d26f0b616718a47cdbeebb6cfbf35b-7.png" class="lazy" alt="Detailed explanation of Python tuples with examples"></p><p>在上述代码中,因为在1-2中没有添加所以,所以当两个元组的优先级相同时会出错;而在3-4中添加了索引,这样就不会出错了!</p><p>推荐学习:<a href="https://www.php.cn/course/list/30.html" target="_blank">python学习教程</a></p>
Copy after login

The above is the detailed content of Detailed explanation of Python tuples with examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view server version of Redis How to view server version of Redis Apr 10, 2025 pm 01:27 PM

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

See all articles