In this article, we introduce in detail Python All existing sequence types and some more advanced usages in .
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 .
These sequence types store the values of objects , They are a continuous storage space , Only one type can be accommodated .
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 .
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')]
But it should be noted that , Don't abuse list derivation :
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]
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 .
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 .
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 .
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)
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])
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 .
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 .
Except that all tuples have attributes and methods , Named tuples also have the following three useful properties and methods .
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 :
《 smooth python》.