Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Tuple Operation examples in Python

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this "Tuple operation case analysis in Python" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Tuple operation case analysis in Python" article.

Introduction

In Python, data structures are used to save important data information in a project. Python language has a variety of built-in data structures, such as lists, tuples, dictionaries and collections. In this lesson, we will talk about the tuple, which is an important structure of big data in Python.

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

1. Creation of tuple & & access (1) creation of tuple:

In Python, the basic form of creating tuples is to enclose data elements in parentheses "()" and separate them with commas.

As follows:

Tuple1 = ('xiaoming',' xiaohong', 18, 21) tuple2 = (1, 2, 3, 4, 5) # and-- empty tuples can be created! Tuple3 = () # Note-if you create a tuple that contains only one element, don't forget to add a comma after the element. Let it be identified as a tuple: tuple4 = (22,) (2) access:

Tuples are similar to strings and lists, with indexes starting at 0 and can be intercepted and combined.

As follows:

Tuple1 = ('xiaoming',' xiaohong', 18, 21) tuple2 = (1, 2, 3, 4, 5) # displays the value print of the element with index 1 in the tuple ("tuple1 [1]:", tuple1 [0]) # displays the value print of the element in the tuple with index from 1 to 3 ("tuple2 [1:3]:", tuple2 [1:3])

two。 Modification of tuple & & delete (1) modification of tuple:

Although tuples are said to be immutable at the beginning, it still has a supported operation-join combinations between tuples:

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

(2) deletion of tuples:

Although tuples are immutable, entire tuples can be deleted through the del statement.

As follows:

Tuple1 = ('xiaoming',' xiaohong', 18,21) print (tuple1) # normal print tuple1del tuple1print (tuple1) # because the tuple1 is deleted above, so printing again will report an error!

3. Built-in methods of tuples

Tuples are immutable, but we can manipulate tuples by using built-in methods. Common built-in methods are as follows:

Len (tuple): calculates the number of tuple elements

Max (tuple): returns the maximum value of the element in the tuple

Min (tuple): returns the minimum value of an element in a tuple

Tuple (seq): converts a list to a tuple.

In fact, more often, we convert tuples to lists first, and then to tuples after operation (because lists have many methods).

4. Decompose a sequence into separate variables

(1)

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

As follows:

Tuple1 = (18,22) x, y = tuple1print (x) print (y) tuple2 = ['xiaoming', 33,19.8, (2012, 1,11)] name, age, level, date = tuple2print (name) print (date)

If you want to decompose an iterable object of unknown or arbitrary length, the above decomposition operation is very nice! Usually there are some known components or patterns in such iterable objects (for example, everything after element 1 is a phone number). After decomposing the iterable object with the "*" asterisk expression, it makes it easy for developers to take advantage of these patterns without having to do complex operations in the iterable object to get the relevant elements.

In Python, asterisk expressions are useful for iterating over a sequence of variable-length 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)

(2)

When iterating over sequences such as lists or tuples in Python, it is sometimes necessary to count the last few records to achieve the history statistics function.

Use the built-in deque implementation:

From _ collections import dequeq = deque (maxlen=3) q.append (1) q.append (2) q.append (3) print (Q) q.append (4) print (Q)

The following-- demonstrates the process of using the last few items in the sequence as historical records.

From _ collections import dequedef 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 fileif _ name__ = ='_ main__': with open ('123.txt') as f: for line, prevlines in search (f,' python' 5): for pline in prevlines: # Line containing python print (pline) # print (pline, end='') # print the last checked N lines of text print (line) # print (pline, end='')

123.txt:

Pythonpythonpythonpythonpythonpythonpython

Python

Python

In the above code, a simple text matching operation is implemented for a series of text lines, and when a suitable match is found, the current matching line and the last checked N-line text are output. A fixed-length queue is created using deque (maxlen=N). When a new record is added and the queue is full, the oldest record is automatically removed. When writing code to search for a record, a generator function with the yield keyword is often used, which successfully decouples the code that handles the search process from the code that uses the search results.

5. Implement priority queues

A simple priority queue can be implemented using the built-in module heapq.

The following-demonstrates the process of implementing a simple priority queue.

Import heapqclass 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 ())

In the above code, a simple priority queue is implemented using the heapq module, and the element returned by the pop () operation for the first time has the highest priority.

Two elements with the same priority (foo and grok) are returned in the same order as they were inserted into the queue.

The functions heapq.heappush () and heapq.heappop () implement the insertion and removal of elements in the list _ queue, respectively, and ensure that the first element in the list has the lowest priority.

The function heappop () always returns the "smallest" element, and because the complexity of both push and pop operations is O (log2N), where N represents the number of elements in the heap, these operations are very efficient even if the value of N is large.

The queues in the above code are in the form of tuples (- priority, index, item). The priority is negative so that the queues can be arranged from top to bottom according to the priority of the elements. This is contrary to the normal order of heap arrangement, which is generally sorted from smallest to largest. The function of the variable index is to arrange the elements with the same priority in the appropriate order, and by maintaining an increasing index, the elements will be arranged in the order in which they were added to the queue. But index also plays an important role when comparing elements with the same priority.

In Python, if elements are stored as tuples (priority, item), they can be compared as long as they have different priorities. However, if the two tuples have the same priority, the comparison operation will fail. At this point, you can consider introducing an additional index value to create tuples in the form of (priority, index, item), because no two tuples will have the same index value, so the above problem can be completely avoided. Once the result of the comparison operation can be determined, Python will not compare the remaining tuple elements.

The following-demonstrates the process of implementing a simple priority queue:

Import heapqclass 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 < b error a = (1, Item ('AAA')) b = (5, Item (' BBB')) print (a < b) c = (1, Item ('CCC')) # ② a < c error # ③ a = (1,0) Item ('AAA')) b = (5,1, Item (' BBB')) c = (1,2, Item ('CCC')) print (a < b) # ④ print (a < c)

In the above code, since no so is added in ① ~ ②, an error occurs when two tuples have the same priority, while an index is added in ③ ~ ④ so that there is no error! The above is about the content of this article on "Analysis of Tuple Operation examples in Python". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report