Idiom for this case?

Ben Finney ben+python at benfinney.id.au
Thu Dec 24 17:30:45 EST 2015


KP <kai.peters at gmail.com> writes:

> Given:
>
> cfg =  {'c': ('3840', '1024'),
>        'p1': {'gpio': '1', 'id': '4', 'coord': ('0', '0', '1280', '1024')}, 
>        'p2': {'gpio': '2', 'id': '5', 'coord': ('1280', '0', '2560', '1024')},
>        'p3': {'gpio': '3', 'id': '6', 'coord': ('2560', '0', '3840', '1024')}}
>
> for config in cfg:
>     if config != 'canvas':
>         print config

Given the above data, none of the keys equal 'canvas', so the comparison
is redundant if that's the data set.

The chosen names are also confusing. It implies that each item of ‘cfg’
is a ‘config’. Can you choose names that better communicate the
semantics of that data structure?

> Is there an idiom that combines the 'for...' & the 'if..' lines into one?

This is an opportunity to learn generator expressions::

    for item in (x for x in cfg if x != canvas):
        print item

<URL:https://docs.python.org/3/reference/expressions.html#generator-expressions>

You will learn about these by working through the Python tutorial, from
beginning to end <URL:https://docs.python.org/3/tutorial/>. Don't skip
anything, and experiment with each example to understand it before
continuing.

-- 
 \      “Anyone who believes exponential growth can go on forever in a |
  `\        finite world is either a madman or an economist.” —Kenneth |
_o__)                                                         Boulding |
Ben Finney




More information about the Python-list mailing list