简体   繁体   中英

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.

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

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