4 ms·
In python I do horrible things like the following when nobody else is going to see it: [[[foo(x) for x in y] for y in bar_vec if baz(y)] for bar_vec in bar_m
by rthomas6 3y ago
In python I do horrible things like the following when nobody else is going to see it:
[[[foo(x) for x in y] for y in bar_vec if baz(y)] for bar_vec in bar_mat if bar_vec != []]
- Arelius 3y agoI dunno, that seems to be just shame instilled by the toxicity of certain programmer culture. I mean, it's not the clearest thing to read but labeling it horrible seems to be a judgement call that's unwarranted. And as software developers, we should create an environment that's less hostile to people who write things in ways we wouldn't. And honestly, that set of list comprehensions has a bit of a lispy functional vibe, which could quite frankly be applauded in certain contexts.
- __MatrixMan__ 3y agoI have my secret perversions as well, so I've got no judgement for you, but I do have to wonder how our editing styles differ if you find that easier to navigate than the equivalent nested for loop.
- rthomas6 3y agofor bar_vec in bar_mat: if bar_vec != []: for y in bar_vec: if baz(y): for x in y: foo(x) Seeing it written out here, the example looks nice. In real code with more complexity, it takes longer for me to write it, and it usually takes up a lot more space than this. It bugs me how much space it takes up for something that is one idea in my head (Foo all the baz things in bar_vec). But if there is anyone coming after me, I would write it in this style for their sake, because this style is easier to change.
- deleted 3y ago[deleted]
- __MatrixMan__ 3y agoAt least in my code, these nested loop thingies are rarely unique. If I have to do it once I probably have to do it many times. If I'm being mindful, I stop repeating myself and just write a generator so that I can invoke it like: [foo(x) for x in nonempty(bar_mat)] Mostly this is because I live in fear of ruff's complexity warning, C901.
- arolihas 3y agoMaybe I'm telling on myself but this doesn't seem that bad at all.
- nicbou 3y agoThis is fine. I make all of my stuff open source, but I'll be honest with people about being the only user that matters to my development work.
- Cyphase 3y agoSide note, you don't need `if bar_vec != []`. Trying to loop over an empty iterable (e.g. a list) just doesn't loop, since there's nothing there. Also, another way to write this (which results in a flattened list) is: [foo(x) for bar_vec in bar_mat for y in bar_vec if baz(y) for x in y]