Parsher
Parsher

Reputation: 66

List comprehension for nested for loops with conditional statements?

I am studying list comprehension and while I have seen much discussion to answer my questions, I have yet to see a code such as below made into a list comprehension.

# example array and counter var

rotated = [['#', '.', 'X', 'X', 'X'], ['.', '.', 'X', 'X', 'X'], ['X', '#', '#', '.', '.'], ['X', 'X', 'X', 'X', 'X']]
shot = 0

# I dont know how to turn the example code below this into its list comprehension form. 

for i in rotated:
        for j in i:
            if j == "#":
                break
            elif j == "X":
                shot += 1

I know its somewhat pointless to not just use it as it is (a nested for loop) but I would like to see if it is possible to write an equivalent list comprehension or a generator expression.

Upvotes: 1

Views: 79

Answers (1)

CDJB
CDJB

Reputation: 14516

You can do this in a one-liner in the following way - use ''.join() to create a string from the characters in each sublist, use split('#')[0] to convert these to everything before the first occurence of #, and then count('X') which gives the number of X characters in the string. Finally, we use sum() to add all the numbers together.

>>> rotated = [['#', '.', 'X', 'X', 'X'], ['.', '.', 'X', 'X', 'X'], ['X', '#', '#', '.', '.'], ['X', 'X', 'X', 'X', 'X']]
>>> sum(''.join(x).split('#')[0].count('X') for x in rotated)
9

Upvotes: 1

Related Questions