程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Advanced usage of Python sequences

編輯:Python

1. introduction

In this article, we introduce in detail Python All existing sequence types and some more advanced usages in .

2. Classification of sequences

2.1. According to the stored content

2.1.1. Store the sequence of references

  • list
  • tuple
  • colletions.deque

Stored in these sequences are references to objects , So they don't care about the type of storage object being referenced , in other words , You can put different types of objects in a sequence .

2.1.2. Store the value of the object

  • str
  • bytes
  • bytearray
  • memoryview
  • array.array

These sequence types store the values of objects , They are a continuous storage space , Only one type can be accommodated .

2.2. According to whether the storage content can be changed

2.2.1. Variable sequence

  • list
  • bytearray
  • array.array
  • collections.deque
  • memoryview

2.2.2. Immutable sequence

  • tuple
  • str
  • bytes

3. The list of deduction — listcomps

3.1. Introduce

The following code converts a string to unicode Code stored in list And output :

>>> symbols = '$¢£¥€¤'
>>> codes = []
>>> for symbol in symbols:
... codes.append(ord(symbol))
...
>>> codes
[36, 162, 163, 165, 8364, 164]

Let's change it to the form of list derivation :

>>> symbols = '$¢£¥€¤'
>>> codes = [ord(symbol) for symbol in symbols]
>>> codes
[36, 162, 163, 165, 8364, 164]

obviously , The method of list derivation greatly simplifies the above code , The logic is more clear and concise , It can very succinctly implement element filtering or processing of iterative types , And create a new list .

3.2. Multiple cycles

We can put multiple loops in the list derivation , For example, the following example of generating Cartesian product :

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> tshirts = [(color, size) for color in colors for size in sizes]
>>> tshirts
[('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'),
('white', 'M'), ('white', 'L')]

3.3. Be careful

But it should be noted that , Don't abuse list derivation :

  1. Just leave the task of creating a new list to list derivation
  2. If the list derivation exceeds two lines , It is better to use for loop

4. lambda expression — filter And map

filter And map combination lambda Expressions can also perform the same functions as list derivation , But readability is greatly reduced . The following example will Unicode Greater than 127 The character corresponding to Unicode Values are added to the list :

>>> symbols = '$¢£¥€¤'
>>> beyond_ascii = [ord(s) for s in symbols if ord(s) > 127]
>>> beyond_ascii
[162, 163, 165, 8364, 164]
>>> beyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols)))
>>> beyond_ascii
[162, 163, 165, 8364, 164]

5. Generator Expressions

In all the above examples , We all only generate lists , If we want to generate other types of sequences , List derivation is not applicable , At this point, the generator expression becomes a better choice . In short , Changing the square brackets derived from the list into parentheses is the generator expression , But in usage , Generator expressions are often used to generate sequences as arguments to methods . The following example calculates a set of Cartesian products using a generator expression :

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
... print(tshirt)

Generators are fundamentally different from list derivation , The generator is actually an inert implementation , He doesn't generate the whole sequence at once , Instead, generate one element at a time , This is very similar to the principle of iterators , If there are many elements in the list , Using the list generator can greatly save memory overhead .

6. Unpacking of tuples

In the last article , We introduced the use of tuples as immutable lists , But an equally important use is to use tuples as records of information .

>>> city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)

You can see , In the above example, only one line of code , Let each element in the tuple be assigned to a different variable , This process is called tuple unpacking .

6.1. Realize variable exchange through tuple unpacking

The following is a very elegant variable exchange operation realized through tuple unpacking :

>>> b, a = a, b

In addition to assigning values to variables , As long as the number of elements of the iteratable object is consistent with the number of elements in the tuple , Any iteratable object can be assigned by unpacking tuples .

6.2. Unpacking of iteratable objects

It can be used * Operator unpacks any iteratable object as a method parameter :

>>> divmod(20, 8)
(2, 4)
>>> t = (20, 8)
>>> divmod(*t)
(2, 4)

6.3. Acquisition of uncertain split results

Python At most one of a series of variables that are allowed to be unpacked and assigned with a value of The starting variable , It is used to receive all variables left after unpacking and assigning values .args It is the most classical way to obtain uncertain parameters .

>>> a, b, *rest = range(5)
>>> a, b, rest
(0, 1, [2, 3, 4])

6.4. Nesting of tuple unpacking

Tuple unpacking can be nested , As long as the tuple nested structure conforms to the nested structure of the expression itself ,Python You can do the right thing .

6.5. Named tuples — collections.namedtuple

Named tuples are tuples with names and field names , He modeled a simple class with tuples . We go through collections.namedtuple Method to build a named tuple :

>>> from collections import namedtuple
>>> City = namedtuple('City', 'name country population coordinates')
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667))

Essentially , Named tuples are still a use of tuples for recording elements .

6.5.1. Properties and methods of named tuples

Except that all tuples have attributes and methods , Named tuples also have the following three useful properties and methods .

  • 【_fields】 — Class properties , Tuples containing all field names of named tuples
  • 【_make()】 — Generate class instances by accepting an iteratable object , Such as City._make(*delphi_data)
  • 【_asdict()】 — Name the named tuple as collections.OrderedDict Type return , Can be used for friendly display

7. Comparison of sequence types

There are many sequence types , Although most people like to use it most of the time list, But know that sometimes you have better choices :

  • list — The most common sequence types , Easy to use , Especially in the addition of elements 、 Random reading and traversal
  • tuple — Tuples , Immutable sequence type
  • set — Set of elements that do not repeat , Action on inclusion ( For example, check whether an element is in the collection ) With special optimization , This kind of operation will be very efficient
  • array.array — about float Objects store bytecode representations , Storage efficiency ratio list Much higher , If the element is a large number of numbers , He will be better than list The choice of
  • collections.deque — It is very convenient to realize the entry and exit operation of elements at both ends of the sequence , Native support for stack and queue data structures

8. Reference material

《 smooth python》.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved