How to format a list and understand words

Listing lists and dictionaries is powerful and fast, but difficult to read. My mental read buffer fills up quickly, especially when they are deeply nested. Is there a way to make them more readable?

+4
source share
2 answers

You're right .;) They are difficult to read, which can also make them difficult to collect and debug. Let's look at the following example:

current_team = dict((k,v) for k,v in list(team.items()) for player in v['player'] if player['year'] == 2013) 

Too many years of programming in C and Java made it difficult for me to read. Understanding is logically divided into different parts, but I still need to really look at it in order to decompose it.

The main thing to remember is that understanding is an expression, not a statement. That way, you can surround the expression with parsers, and then use implicit line concatenation to add line breaks that organize the expression based on its nesting levels:

 current_players = (dict((k,v) for k,v in list(team.items()) for player in v['player'] if player['year'] == 2013)) 

It becomes clearer here that "the last index is the fastest, just like nested for loops. "

You can even add blank lines and comments:

 current_players = (dict((k,v) # dict comprehension: for k,v in list(team.items()) # let's filter the team member dict... for player in v['player'] # for players... if player['year'] == 2013)) # who are playing this year 

One note: the Python manual says that "indenting continuation lines doesn't matter." Thus, you can use any form of indentation to improve readability, but the interpreter will not perform any additional checks.

+11
source

Another approach is to preserve the power of concepts, but build generators on generators to remove nesting, and then use the built-in list / set / dict , etc ... - something similar to:

 {k:v for k, v in enumerate(range(10)) if v % 2 == 0} 

It can be divided into:

 with_idx = enumerate(range(10)) is_even = (el for el in with_idx if el[1] % 2 == 0) as_dict = dict(is_even) 

Which is actually more detailed, but if you apply similar logic to nested levels, it really makes sense.

+1
source

Source: https://habr.com/ru/post/1484746/


All Articles