3 ms·
I think the easiest way to understand the code is just to switch the loops around, like this: state = [st for st in states[(s,letter)] for s in state]
by cousin_it 15y ago
I think the easiest way to understand the code is just to switch the loops around, like this:
state = [st for st in states[(s,letter)] for s in state]
- acqq 15y agoNot the same, the loop you suggest doesn't work when s is not initialized before: >>> state [0, 1, 2] >>> states [[11, 12], [21, 22], [31, 32]] >>> s=None >>> [ st for st in states[ s ] for s in state ] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not NoneType >>> s >>> [ st for s in state for st in states[ s ] ] [11, 12, 21, 22, 31, 32]
- cousin_it 15y agoThanks! Ouch, indeed my code doesn't work. I didn't test it, but honestly expected it to work. In fact it still seems perverse to me that Python doesn't allow consistent right-to-left scoping in comprehensions! In other words, given a list of lists: z = [[1],[2],[3]] Python wants me to write something like this: [x for y in z for x in y] instead of the more natural-looking: [x for x in y for y in z] Does this feel weird to anyone else? Are there any good reasons why Python can't allow both?
- llimllib 15y ago> Are there any good reasons why Python can't allow both? That is, you want [a for b in c for a in b] to represent both foreach(c, foreach(b)) and foreach(b, foreach(c))? Surely it must choose one or the other. You can sensibly argue that the order should be reversed, but not that python should allow both. There should be only one obvious way to do things. > Does this feel weird to anyone else? Not to me; [(x,y) for x in a for y in b] translates simply to: ret = [] for x in a: for y in b: ret.append((x,y))
- deleted 15y ago[deleted]
- cousin_it 15y agoYeah, you're right. Allowing both is a non-starter. Well, it could try to infer the direction by looking which way the bindings go, e.g. [a for b in c for a in b] would represent foreach(c, foreach(b)) because otherwise b would be unbound in the outer loop... but that doesn't sound like an especially good idea, having syntax change depending on which variable bindings exist. So all in all, I guess I'd prefer it to always go right-to-left: [a for a in b for b in c]. That would be consistent with nested comprehensions (which read right-to-left), but not with nested loops (which read top-to-bottom). YMMV.
- deleted 15y ago[deleted]