Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 24 15:39:51 CET 2014


On Mon, 24 Mar 2014 23:53:12 +1100, Chris Angelico wrote:

> On Mon, Mar 24, 2014 at 11:36 PM, Marko Rauhamaa <marko at pacujo.net>
> wrote:
>>> def get_oneth_element_index(item):
>>>     return item[1].index
>>> L.sort(key=get_oneth_element_index)
>>>
>>> Or do you just shortcut the whole thing by inlining it?
>>>
>>> L.sort(key=lambda item:item[1].index)
>>
>> I still prefer the "def" variant. It even allows you to clarify the
>> meaning of the tuple slot by using a nicer name.
> 
> It's the index of element 1. What more do you need to know? Is it
> actually any help to give that a name? All you gain is a chance for the
> name, the purpose, and the functionality to come into disagreement.



# Magic constants are wicked. Never use a constant without naming it.
ELEMENT_TO_USE_FOR_INDEXING_WHEN_SORTING_L = 1

# <summary>
#     key func used when sorting L, returns item's 1th elem index method
# </summary>
# <function_name>
#    _get_oneth_element_index_to_use_as_keyfunc_when_sorting_L
# </function_name>
# <author>Steven D'Aprano</author>
# <date_created>2014-03-25</date_created>
# <date_modified>2014-03-25</date_modified>
# <revision>1</revision>
# <param name="item">item to be sorted</param>
# <returns>index method of the oneth element</returns>
# <raises>NameError</raises>  # FIXME can this fail any other way?
def _get_oneth_element_index_to_use_as_keyfunc_when_sorting_L(item):
    """Private key function for sorting list L.

    Returns the index method of element 1 of the given item.

    Example of use:

    >>> item = (None, '')
    >>> _get_oneth_element_index_to_use_as_keyfunc_when_sorting_L(item)
    <built-in method index of str object at ...>

    Relies on global constant ELEMENT_TO_USE_FOR_INDEXING_WHEN_SORTING_L.
    May raise NameError if that constant is missing.

    Warning: do not use this for anything else.
    """
    return item[ELEMENT_TO_USE_FOR_INDEXING_WHEN_SORTING_L].index

L.sort(key=_get_oneth_element_index_to_use_as_keyfunc_when_sorting_L)
del _get_oneth_element_index_to_use_as_keyfunc_when_sorting_L
# Better to be safe than sorry.
del ELEMENT_TO_USE_FOR_INDEXING_WHEN_SORTING_L




Definitely being paid by the line :-)


-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list