简体   繁体   中英

list comprehension with concurrent loops python

Simple question as i just want to write more pythonic code. I want to convert the following into 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

What i don't understand is how to walk through the counts list. I don't want a nested for like:

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

The code i have now is working but I'd like to understand python better and use the language as it should be used.

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])

Don't.

List comprehensions are not by definition more pythonic than simple loops - only if these loops are designed to build new lists (or dicts, sets etc.), and if the listcomp is easier to read than the loop.

This is not the case in your example (you're not building anything), and you shouldn't use a listcomp only for its side effects, that would be patently unpythonic.

So it's good to convert

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

into

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

but not your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM