Daily python-- zip () module Detailed

zip(*iterable)

zip () function is a built-in function python, the object subjected to a series of iterations, then the corresponding element value is returned in the form of tuples in python3, the final return value is not displayed in the object list, if necessary display list required ( ) conversion.

>>> a =[1,2,3]
>>> b =[4,5,6]
>>> zipped =zip(a,b)
>>> zipped
<zip object at 0x000001C04141C648>
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(*zipped))
[]
>>> zipped =zip(a,b)
>>> list(zip(*zipped))
[(1, 2, 3), (4, 5, 6)]

Note that the above 9. What behavior will return an empty list? Because the zip () function to create a function can be accessed only once, when () operation in the list, have already visited, so empty and then manipulate it.

Let's look at an example of a two-dimensional matrix transformation (interchanging rows)

>>> c =[[1,2,3],[4,5,6],[7,8,9]]
>>> list(zip(*c))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list, zip(*c))
<map object at 0x000001C041405E10>
>>> list(map(list, zip(*c)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

As can be seen from the above examples zip () with an asterisk and differences without an asterisk, for a list of objects already contained iteration, the asterisk is a decompression operation, the first extract from the internal list, and then combine into a tuple.

Finally, look at operations on a dictionary, if you want to sort the dictionary how to do? Directly sorted () action on a key role in this case, the dictionary can be the first zip () operation, so that the position of the key exchange, and then sorted () operation, according to the values ​​obtained at this time is the size of the dictionary sorted while retaining the corresponding key information.

prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
}
prices_sorted = sorted(zip(prices.values(), prices.keys()))
# prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'),
#                   (45.23, 'ACME'), (205.55, 'IBM'),
#                   (612.78, 'AAPL')]

More exciting, attention to "gnaw home"

5873968-2c9b55c5b23d499d.png
Ye home

Reproduced in: https: //www.jianshu.com/p/fa0a4fb32600

Guess you like

Origin blog.csdn.net/weixin_34408624/article/details/91251347