Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain to me what this python code means?

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(';')]
like image 725
Yan Gao Avatar asked Apr 01 '13 21:04

Yan Gao


People also ask

What is meant by Python code?

Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general-purpose language, meaning it can be used to create a variety of different programs and isn't specialized for any specific problems.

What is Python with example?

What is Python? Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python is dynamically-typed and garbage-collected programming language. It was created by Guido van Rossum during 1985- 1990.

What is Python in one word answer?

Python is a high-level, general-purpose, interpreted object-oriented programming language. Similar to PERL, Python is a programming language popular among experienced C++ and Java programmers.


1 Answers

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.

like image 186
abarnert Avatar answered Sep 21 '22 22:09

abarnert