Pythonic way to unpack an iterator inside of a list

后端 未结 5 929
醉酒成梦
醉酒成梦 2020-12-30 16:24

I\'m trying to figure out what is the pythonic way to unpack an iterator inside of a list.

For example:

my_iterator = zip([1, 2, 3, 4], [1, 2, 3, 4]         


        
5条回答
  •  醉酒成梦
    2020-12-30 16:51

    While the unpacking operator * is not often used for unpacking a single iterable into a list (therefore [*it] is a bit less readable than list(it)), it is handy and more Pythonic in several other cases:

    1. Unpacking an iterable into a single list / tuple / set, adding other values:

    mixed_list = [a, *it, b]
    

    This is more concise and efficient than

    mixed_list = [a]
    mixed_list.extend(it)
    mixed_list.append(b)
    

    2. Unpacking multiple iterables + values into a list / tuple / set

    mixed_list = [*it1, *it2, a, b, ... ]
    

    This is similar to the first case.

    3. Unpacking an iterable into a list, excluding elements

    first, *rest = it
    

    This extracts the first element of it into first and unpacks the rest into a list. One can even do

    _, *mid, last = it
    

    This dumps the first element of it into a don't-care variable _, saves last element into last, and unpacks the rest into a list mid.

    4. Nested unpacking of multiple levels of an iterable in one statement

    it = (0, range(5), 3)
    a1, (*a2,), a3 = it          # Unpack the second element of it into a list a2
    e1, (first, *rest), e3 = it  # Separate the first element from the rest while unpacking it[1]
    

    This can also be used in for statements:

    from itertools import groupby
    
    s = "Axyz123Bcba345D"
    for k, (first, *rest) in groupby(s, key=str.isalpha):
        ...
    

提交回复
热议问题