Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

breaking down list comprehension in python [duplicate]

Tags:

python

I have this one line comprehension and am trying to break it down to understand it:

 units = dict((s, [u for u in unitlist if s in u]) for s in boxes)

So far I have come up with this but it doesn't give the same output:

u = []
for s in boxes:
    for u in unitlist:
        if s in u:
            u.append(u)
            units = dict(u)

please advise, and also please guide me to any place i can understand how to switch between the two better. I find it easier to understand code without the one liners.

like image 475
mountainwater Avatar asked Dec 30 '22 17:12

mountainwater


1 Answers

Original expression with list comprehension:

units = dict((s, [u for u in unitlist if s in u]) for s in boxes)

Classical reproduction:

units = {}

for s in boxes:
    values = []
    for u in unitlist:
        if s in u:
            values.append(u)

    units[s] = values

Your original expression says "make a dict() composed of key, value pairs with s as key and a sublist of unitlist as value"

Your expression also says there is a condition: although all s in boxes will be found as keys in your units dict, the associated values will be equal or a sublist of u.

like image 164
Synthase Avatar answered Jan 02 '23 06:01

Synthase