Tutorial # python data structures and algorithms (1)

Data Structures and Algorithms

Python provides a number of built-in data structures, including lists, sets, and dictionaries. In most cases the
These data structures are used very simple. However, we will often encounter to such queries, sorting and filtering, and so this
Some common problems. Therefore, the purpose of this chapter is to discuss these issues and more common algorithm. In addition,
Our method of operation is also given in a set of data structures such collections among modules.
1.1 decompression sequence assigned to multiple variables
problem
Now there is a tuple or a sequence comprising N elements, while how to assign a value after decompression inside it
To N variables?
solution
Any sequence (or iterable) by a simple assignment statement unpacked and assigned to more than
Variables. The only prerequisite is that the number of variables must be followed by the number of elements in the sequence is the same.
Code Example:
>>> (6, 8)
>>> x, y p
>>> x
6
>>> y
8
>>>
>>> data 'ACME'5091.1, (201911, 17) ]
>>> name, shares, price, date data
>>> name
'ACME'
>>> date
(2019, 11, 17)
>>> name, shares, price, (year, mon, day) data
>>> name
'ACME'
>>> year
2019
>>>  my
11
>>> day
17
>>>
If the number of variables and the number of sequence elements do not match, an exception is generated.
Code Example:
>>> p = (6, 8)
>>> x, y, z = p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
>>>
discuss
Indeed, such an assignment can be used in any decompression iterables above, rather than list or tuple.
A string, a file object, iterators and generators.
Code Example:
>>> 'Hello'
>>> a, b, c, d, e s
>>> a
'H'
>>> b
'e'
>>> e
'The'
>>>
Sometimes you might just want to extract the part, discarding other values. In this case Python did not mention
For special syntax. But you can use any variable name to the placeholder, to the time lost these variables on the line.
Code Example:
>>> data 'ACME'5091.1, (20121221) ]
>>> _, shares, price, _ data
>>> shares
50
>>> price
91.1
>>>
You must ensure that you choose those occupying the variable name is not used to in other places.
1.2 decompression iterables assigned to a plurality of variables
problem
If a number of elements in iterable exceeds the number of variables, it will throw a ValueError. Then
How can unzip this iterables out N elements out?
 
solution
An asterisk Python expressions can be used to solve this problem. For example, you study a course in the semester
At the end, you want to lower the average score statistics homework, but exclude first and last scores. in case
Only four points, you may go directly to a simple manual assignment, but if you have 24 it? This time expression asterisk
Formula comes in handy:
def drop_first_last(grades):
first, *middle, last grades
return avg(middle)
Another case, assume that you now have a list of records of some users, each record contains a name, postal
Pieces, followed by an unspecified number of phone numbers. In this way you can break down these records as follows:
>>> record ('Dave''[email protected]''773-555-1212''847-555-1212')
>>> name, email, *phone_numbers record
>>> name
'Dave'
>>> email
>>> phone_numbers
['773-555-1212', '847-555-1212']
>>>
It is noteworthy that extract the above phone_numbers variable is always the type of list, regardless of decompression
The telephone number is how many numbers (including zero). Therefore, any use of the variable code is not phone_numbers
You need to do the extra type checking to confirm whether it is the type of list.
An asterisk expression can also be used in the beginning of the list. For example, you have eight months before a company sales data
Sequence, but you want to see the contrast of the month the average of recent data and the previous seven months. You can do this:
*trailing_qtrs, current_qtr sales_record
trailingavg  sum (trailingqtrs)  len (trailingqtrs)
return avg_comparison(trailing_avg, current_qtr)
The following is a result of the execution in the Python interpreter:
>>> *trailing, current [1087195103]
>>> trailing
[10, 8, 7, 1, 9, 5, 10]
>>> current
3
discuss
Extended iteratively decompressed syntax is designed for extracting uncertain number or any number of elements and set iterable
Meter. Typically, the structure of these elements are determined iterables rules (such as the back of the first element are electrically
Phone number), asterisk expressions allow developers to easily take advantage of these rules to extract the elements. Instead of
To get the value of these elements associated by some of the more sophisticated means.
 
 
It is noteworthy that the asterisk in the expression for the iteration variable sequence element tuple length is very useful. such as,
The following is a sequence of tuples of a tag having:
records [
('foo'12),
('bar''hello'),
('foo'34),
]
def do_foo(x, y):
print ( 'foo' , x, y)
def do_bar(s):
print('bar', s)
for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif  tag  ==  'bar' :
do_bar(*args)
An asterisk at the time of decompression syntax string manipulation will be useful, such as splitting the string.
Code Example:
>>> line 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
>>> uname, *fields, homedir, sh line.split(':')
>>> uname
'nobody'
>>> homedir
'/var/empty'
>>> sh
'/usr/bin/false'
>>>
Sometimes, after extracting some elements you want to discard them, you can not simply use it *, but you can use a
Ordinary waste names, such as _ or ign (ignore).
Code Example:
>>> record ('ACME'50123.45, (12182012))
>>> name, *_, (*_, year) record
>>> name
'ACME'
>>> year
2012
>>>
In many functional language, grammar asterisk decompression process has many similarities with the list. For example, if you have
A list, you can easily split it into two parts before and after:
 
>>> items [1107459]
>>> head, *tail items
>>> head
1
>>> tail
[10, 7, 4, 5, 9]
>>>
If you're smart enough, you can also use this syntax to split clever implementation recursive algorithm. such as:
>>> def sum(items):
...
head, *tail items
...
return head sum(tail) if tail else head
...
>>> sum(items)
36
>>>
Then, due to the language level, Python is not good at recursion. Therefore, the last play that recursion
Shows just the curious to explore fills this not too seriously.
 
 
 

Guess you like

Origin www.cnblogs.com/winterhai/p/11877527.html