简体   繁体   中英

Python syntax error in list comprehension?

Professor introduced a new way to write some code.

x=[1,2,3,4,5,6,7,8,9]
y=[i<6 , for i in x]
print(y)

I am expecting the following output

True, True, True, True, True, False, False, False, False

Is there a syntax error in the y statement? My program is highlight the for part.

You don't use , in a list comprehension. This works fine:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

y = [i<6 for i in x]

print(y)

Returns [True, True, True, True, True, False, False, False, False]

What your professor is teaching you is list comprehension . I love them. Succinct to write.

Alternatively, you could have written it like this, which is way longer:

z = []

for i in x:
    if i < 6:
        z.append(True)
    else:
        z.append(False)

print(z)

Would return [True, True, True, True, True, False, False, False, False]

By the way, the above code can also be written with shorthand if else syntax:

    z = []
    for i in x:
        z.append(True) if i < 6 else z.append(False)
    return z

Anyway, here is a more full solution with unit testing for your perusal.

import unittest

def so_26923986(x):

    y = [i < 6 for i in x]
    return y 

def so_26923986_1(x):

    z = []
    for i in x:
        z.append(True) if i < 6 else z.append(False)
    return z

Unit Test

# Unit Test
class Test(unittest.TestCase):
    def testcase(self):
        self.assertEqual(so_26923986([1, 2, 3, 4, 5, 6, 7, 8, 9]), [True, True, True, True, True, False, False, False, False])
        self.assertEqual(so_26923986_1([1, 2, 3, 4, 5, 6, 7, 8, 9]), [True, True, True, True, True, False, False, False, False])

        self.assertEqual(so_26923986([1, 2, 3]), [True, True, True])
        self.assertEqual(so_26923986_1([1, 2, 3]), [True, True, True])

        self.assertEqual(so_26923986([1, 2, 7, 10, 3, 8]), [True, True, False, False, True, False])
        self.assertEqual(so_26923986_1([1, 2, 7, 10, 3, 8]), [True, True, False, False, True, False])

unittest.main()

Test Passing

Ran 1 test in 0.000s

OK

You should write like :

    x=[1,2,3,4,5,6,7,8,9]
    y=[i<6 for i in x]
    print y

Your code is fine but remove , from list.

output :

   [True, True, True, True, True, False, False, False, False]

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