简体   繁体   中英

What is the explanation of the following list comprehension?

input_shape = tuple([i for i in input_shape if i is not None])

I am new to python and don't understand what's happening there. As I see it is possible to be some analog of C 's int a = 5 > 2 ? val1 : val2; int a = 5 > 2 ? val1 : val2; , but I can't figure it out.

I tried to separate it on small parts to understand, but it still makes no sense for me. Like that:

i // this is already wrong for being single
for i in input_shape //that's correct for cicle
    if i is not None //ugh... so, and what if?

Items that fail the test (that are None here) will be skipped by the loop.

input_shape = tuple([i for i in input_shape if i is not None])

# Roughly equivalent to    

result = []
for i in input_shape:
    if i is not None:
        result.append(i)
input_shape = tuple(result)

Conceptually the same, except the list comprehension will be faster as the looping is done internally by the interpreter. Also, it will not leave a result variable around, obviously.

the i for i part can be anything, x for x , y for y , or even Kosmos for Kosmos .

>>> input_shape = [1, 2, 3]
>>> input_shape = tuple([i for i in input_shape if i is not None])
>>> input_shape
(1, 2, 3)

Here you can see, it converted my list to a tuple by looping over each item.

Look into a thing called list comprehension, as I am having a tough time explaining it

input_shape = [1,2,3,None,5,1]
print(input_shape)
input_shape = tuple([i for i in input_shape if i is not None])
print(input_shape)

o/p

[1, 2, 3, None, 5, 1]
(1, 2, 3, 5, 1)

as @spectras pointed, Items that fail the test (that are None here) will be skipped by the loop.

The following is a list comprehension :

[i for i in input_shape if i is not None]

It returns only elements that are not None

Then, you call tuple() to convert the resulted list to tuple.

You can achieve the same result by using an ordinary for loop like below:

input_shape = [1, 2, None, 'a', 'b', None]
result = []

for i in input_shape:
    if i is not None:
        result.append(i)

print(result)
# Output: [1, 2, 'a', 'b']

Now, we convert result (of type list ) to tuple like this:

final_result = tuple(result)
print(final_result)
# Output: (1, 2, 'a', 'b')

You were almost there with your separation. The inner part (what if) is the expression you noted being wrong ( i ), it actually goes inside. And what it does with it is expressed by being inside brackets [] ; it puts those things in a list. spectras' answer shows how this works using a variable to hold that list. The construct is called a list comprehension .

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