I still learn python but this code seems beyond my level. what does it means?
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
I still learn python but this code seems beyond my level. what does it means?
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
You can convert any list comprehension to an equivalent explicit loop like this:
pairs = []
for s1 in qs.split('&'):
for s2 in s1.split(';'):
pairs.append(s2)
The rule is to take all of the for
and if
clauses, nest them in the order they appear, and then append(foo)
for whatever foo
comes before the first clause.
The tutorial section on List Comprehension (and the subsection on Nested List Comprehensions) explains this… but it doesn't give you the simple rule for converting any comprehension into a nested block statement, which (in my opinion) makes it much easier to understand all but the trivial cases.
It's also worth noting that urllib.parse.parse_qsl
(or urlparse.parse_qsl
in 2.x) is a better way to parse query strings. Besides the fact that it doesn't involve a hard-to-read nested list comprehension, it also properly handles all kinds of things (like quoting) that you wouldn't think about in advance, and will end up debugging for one of your users who doesn't know how to submit useful bug reports.