Python parallel loops list

A simple question as I just want to write more pythonic code. I want to convert the following to a list comprehension

index_row = 0 for row in stake_year.iterrows(): self.assertTrue(row[0] == counts[index_row][0]) self.assertTrue(row[1][0] == counts[index_row][1]) index_row += 1 

I don’t understand how to get through the list of calculations. I do not want nested for:

 [self.assertTrue(x[0] == counts[y][0] for x in stake_year for y in counts] 

Now I have the code, but I would like to understand python better and use this language as it should be used.

+5
source share
2 answers

The more pythonic way to use in your case is to use enumerate :

 for index_row, row in enumerate(stake_year.iterrows()): self.assertTrue(row[0] == counts[index_row][0]) self.assertTrue(row[1][0] == counts[index_row][1]) 
+7
source

Not.

Explanations of lists are by definition no longer pythonic than simple loops - only if these loops are for creating new lists (or dicts, sets, etc.), and if listcomp is easier to read than a loop.

This is not the case in your example (you are not building anything), and you should not use listcomp only for your side effects, which would be clearly non-python.

So good to convert

 result = [] for line in lines: result.append(line.upper()) 

in

 result = [line.upper() for line in lines] 

but not your example.

+5
source

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


All Articles