pytorch_ common python operations

a list operation

1.1 zip()、zip(*)

Python's zip() function is defined as zip(*iterables). This function takes an iterable object as an argument and returns an iterator. This iterator produces a sequence of tuples containing elements from each iterable . zip() can accept any type of iterable object, such as files, lists, tuples, dictionaries, sets, etc.

Code example:

>>> numbers = [1, 2, 3]
>>> letters = ['a', 'b', 'c']
>>> zipped = zip(numbers, letters)
>>> zipped  # Holds an iterator object
<zip object at 0x7fa4831153c8>
>>> type(zipped)
<class 'zip'>
>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]

Here, use zip(numbers, letters) to create an iterator that yields tuples of the form (x, y). In this case, the x values ​​are taken from the numbers and the y values ​​are taken from the letters. Note how the Python zip() function returns an iterator. To retrieve the final list object, use an iterator using list().

Note that when using sequences such as lists, tuples, or strings , iterables are guaranteed to be evaluated left-to-right. This means that the resulting list of tuples will be of the form [(numbers[0], letters[0]), (numbers[1], letters[1]),..., (numbers[n], letters[n ]) ]. However, you may see some strange results with other types of iterable objects such as collections :

>>> s1 = {
    
    2, 3, 1}
>>> s2 = {
    
    'b', 'a', 'c'}
>>> list(zip(s1, s2))
[(1, 'a'), (2, 'c'), (3, 'b')]

You can refer to: 1. Detailed explanation is very detailed
2. Thoroughly understand zip
and other high-level gameplay will be updated from time to time

Guess you like

Origin blog.csdn.net/qq_38765642/article/details/127844536